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.Date;
37 import java.util.GregorianCalendar;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.List;
43 import java.util.TreeMap;
44 import java.util.UUID;
46 import javax.servlet.http.HttpServletRequest;
48 import org.onap.aaf.auth.common.Define;
49 import org.onap.aaf.auth.dao.DAOException;
50 import org.onap.aaf.auth.dao.cass.ApprovalDAO;
51 import org.onap.aaf.auth.dao.cass.CertDAO;
52 import org.onap.aaf.auth.dao.cass.CredDAO;
53 import org.onap.aaf.auth.dao.cass.DelegateDAO;
54 import org.onap.aaf.auth.dao.cass.FutureDAO;
55 import org.onap.aaf.auth.dao.cass.HistoryDAO;
56 import org.onap.aaf.auth.dao.cass.Namespace;
57 import org.onap.aaf.auth.dao.cass.NsDAO;
58 import org.onap.aaf.auth.dao.cass.NsDAO.Data;
59 import org.onap.aaf.auth.dao.cass.NsSplit;
60 import org.onap.aaf.auth.dao.cass.NsType;
61 import org.onap.aaf.auth.dao.cass.PermDAO;
62 import org.onap.aaf.auth.dao.cass.RoleDAO;
63 import org.onap.aaf.auth.dao.cass.Status;
64 import org.onap.aaf.auth.dao.cass.UserRoleDAO;
65 import org.onap.aaf.auth.dao.hl.CassExecutor;
66 import org.onap.aaf.auth.dao.hl.Function;
67 import org.onap.aaf.auth.dao.hl.Function.FUTURE_OP;
68 import org.onap.aaf.auth.dao.hl.Function.Lookup;
69 import org.onap.aaf.auth.dao.hl.Function.OP_STATUS;
70 import org.onap.aaf.auth.dao.hl.Question;
71 import org.onap.aaf.auth.dao.hl.Question.Access;
72 import org.onap.aaf.auth.env.AuthzTrans;
73 import org.onap.aaf.auth.layer.Result;
74 import org.onap.aaf.auth.org.Executor;
75 import org.onap.aaf.auth.org.Organization;
76 import org.onap.aaf.auth.org.Organization.Expiration;
77 import org.onap.aaf.auth.org.Organization.Identity;
78 import org.onap.aaf.auth.org.Organization.Policy;
79 import org.onap.aaf.auth.org.OrganizationException;
80 import org.onap.aaf.auth.rserv.doc.ApiDoc;
81 import org.onap.aaf.auth.service.mapper.Mapper;
82 import org.onap.aaf.auth.service.mapper.Mapper.API;
83 import org.onap.aaf.auth.service.validation.ServiceValidator;
84 import org.onap.aaf.auth.validation.Validator;
85 import org.onap.aaf.cadi.principal.BasicPrincipal;
86 import org.onap.aaf.misc.env.Env;
87 import org.onap.aaf.misc.env.TimeTaken;
88 import org.onap.aaf.misc.env.util.Chrono;
89 import org.onap.aaf.misc.env.util.Split;
91 import aaf.v2_0.CredRequest;
94 * AuthzCassServiceImpl implements AuthzCassService for
109 public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS>
110 implements AuthzService <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> {
112 private Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper;
114 public Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper() {return mapper;}
116 private static final String ASTERIX = "*";
117 private static final String CACHE = "cache";
118 private static final String ROOT_NS = Define.ROOT_NS();
119 private static final String ROOT_COMPANY = Define.ROOT_COMPANY();
121 private final Question ques;
122 private final Function func;
124 public AuthzCassServiceImpl(AuthzTrans trans, Mapper<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper,Question question) {
125 this.ques = question;
126 func = new Function(trans, question);
127 this.mapper = mapper;
131 /***********************************
133 ***********************************/
136 * @throws DAOException
137 * @see org.onap.aaf.auth.service.AuthzService#createNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String)
144 errorCodes = { 403,404,406,409 },
145 text = { "Namespace consists of: ",
146 "<ul><li>name - What you want to call this Namespace</li>",
147 "<li>responsible(s) - Person(s) who receive Notifications and approves Requests ",
148 "regarding this Namespace. Companies have Policies as to who may take on ",
149 "this Responsibility. Separate multiple identities with commas</li>",
150 "<li>admin(s) - Person(s) who are allowed to make changes on the namespace, ",
151 "including creating Roles, Permissions and Credentials. Separate multiple ",
152 "identities with commas</li></ul>",
153 "Note: Namespaces are dot-delimited (i.e. com.myCompany.myApp) and must be ",
154 "created with parent credentials (i.e. To create com.myCompany.myApp, you must ",
155 "be an admin of com.myCompany or com"
159 public Result<Void> createNS(final AuthzTrans trans, REQUEST from, NsType type) {
160 final Result<Namespace> rnamespace = mapper.ns(trans, from);
161 final ServiceValidator v = new ServiceValidator();
162 if (v.ns(rnamespace).err()) {
163 return Result.err(Status.ERR_BadData,v.errs());
165 final Namespace namespace = rnamespace.value;
166 final Result<NsDAO.Data> parentNs = ques.deriveNs(trans,namespace.name);
167 if (parentNs.notOK()) {
168 return Result.err(parentNs);
171 if (namespace.name.lastIndexOf('.')<0) { // Root Namespace... Function will check if allowed
172 return func.createNS(trans, namespace, false);
175 Result<FutureDAO.Data> fd = mapper.future(trans, NsDAO.TABLE,from,namespace,true,
178 public String get() {
179 return "Create Namespace [" + namespace.name + ']';
183 private Result<NsDAO.Data> rnd;
185 public Result<?> mayChange() {
187 rnd = ques.mayUser(trans, trans.user(), parentNs.value,Access.write);
194 Result<String> rfc = func.createFuture(trans, fd.value, namespace.name, trans.user(),parentNs.value, FUTURE_OP.C);
196 return Result.err(Status.ACC_Future, "NS [%s] is saved for future processing",namespace.name);
198 return Result.err(rfc);
201 return func.createNS(trans, namespace, false);
203 return Result.err(fd);
209 path = "/authz/ns/:ns/admin/:id",
210 params = { "ns|string|true",
214 errorCodes = { 403,404,406,409 },
215 text = { "Add an Identity :id to the list of Admins for the Namespace :ns",
216 "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" }
219 public Result<Void> addAdminNS(AuthzTrans trans, String ns, String id) {
220 return func.addUserRole(trans, id, ns,Question.ADMIN);
225 path = "/authz/ns/:ns/admin/:id",
226 params = { "ns|string|true",
230 errorCodes = { 403,404 },
231 text = { "Remove an Identity :id from the list of Admins for the Namespace :ns",
232 "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" }
235 public Result<Void> delAdminNS(AuthzTrans trans, String ns, String id) {
236 return func.delAdmin(trans,ns,id);
241 path = "/authz/ns/:ns/responsible/:id",
242 params = { "ns|string|true",
246 errorCodes = { 403,404,406,409 },
247 text = { "Add an Identity :id to the list of Responsibles for the Namespace :ns",
248 "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)" }
251 public Result<Void> addResponsibleNS(AuthzTrans trans, String ns, String id) {
252 return func.addUserRole(trans,id,ns,Question.OWNER);
257 path = "/authz/ns/:ns/responsible/:id",
258 params = { "ns|string|true",
262 errorCodes = { 403,404 },
263 text = { "Remove an Identity :id to the list of Responsibles for the Namespace :ns",
264 "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)",
265 "Note: A namespace must have at least 1 responsible party"
269 public Result<Void> delResponsibleNS(AuthzTrans trans, String ns, String id) {
270 return func.delOwner(trans,ns,id);
274 * @see org.onap.aaf.auth.service.AuthzService#applyModel(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object)
278 path = "/authz/ns/:ns/attrib/:key/:value",
279 params = { "ns|string|true",
281 "value|string|true"},
283 errorCodes = { 403,404,406,409 },
285 "Create an attribute in the Namespace",
286 "You must be given direct permission for key by AAF"
290 public Result<Void> createNsAttrib(AuthzTrans trans, String ns, String key, String value) {
291 TimeTaken tt = trans.start("Create NsAttrib " + ns + ':' + key + ':' + value, Env.SUB);
294 final Validator v = new ServiceValidator();
295 if (v.ns(ns).err() ||
297 v.value(value).err()) {
298 return Result.err(Status.ERR_BadData,v.errs());
301 // Check if exists already
302 Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
303 if (rlnsd.notOKorIsEmpty()) {
304 return Result.err(rlnsd);
306 NsDAO.Data nsd = rlnsd.value.get(0);
308 // Check for Existence
309 if (nsd.attrib.get(key)!=null) {
310 return Result.err(Status.ERR_ConflictAlreadyExists, "NS Property %s:%s exists", ns, key);
313 // Check if User may put
314 if (!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB,
315 ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) {
316 return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key);
320 nsd.attrib.put(key, value);
321 ques.nsDAO.dao().attribAdd(trans,ns,key,value);
330 path = "/authz/ns/attrib/:key",
331 params = { "key|string|true" },
333 errorCodes = { 403,404 },
335 "Read Attributes for Namespace"
339 public Result<KEYS> readNsByAttrib(AuthzTrans trans, String key) {
341 final Validator v = new ServiceValidator();
342 if (v.nullOrBlank("Key",key).err()) {
343 return Result.err(Status.ERR_BadData,v.errs());
347 if (!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB,
348 ":"+trans.org().getDomain()+".*:"+key, Question.READ)) {
349 return Result.err(Status.ERR_Denied,"%s may not read NS by Attrib '%s'",trans.user(),key);
352 Result<Set<String>> rsd = ques.nsDAO.dao().readNsByAttrib(trans, key);
354 return Result.err(rsd);
356 return mapper().keys(rsd.value);
362 path = "/authz/ns/:ns/attrib/:key/:value",
363 params = { "ns|string|true",
366 errorCodes = { 403,404 },
368 "Update Value on an existing attribute in the Namespace",
369 "You must be given direct permission for key by AAF"
373 public Result<?> updateNsAttrib(AuthzTrans trans, String ns, String key, String value) {
374 TimeTaken tt = trans.start("Update NsAttrib " + ns + ':' + key + ':' + value, Env.SUB);
377 final Validator v = new ServiceValidator();
378 if (v.ns(ns).err() ||
380 v.value(value).err()) {
381 return Result.err(Status.ERR_BadData,v.errs());
384 // Check if exists already (NS must exist)
385 Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
386 if (rlnsd.notOKorIsEmpty()) {
387 return Result.err(rlnsd);
389 NsDAO.Data nsd = rlnsd.value.get(0);
391 // Check for Existence
392 if (nsd.attrib.get(key)==null) {
393 return Result.err(Status.ERR_NotFound, "NS Property %s:%s exists", ns, key);
396 // Check if User may put
397 if (!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB,
398 ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) {
399 return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key);
403 nsd.attrib.put(key, value);
405 return ques.nsDAO.update(trans,nsd);
414 path = "/authz/ns/:ns/attrib/:key",
415 params = { "ns|string|true",
418 errorCodes = { 403,404 },
420 "Delete an attribute in the Namespace",
421 "You must be given direct permission for key by AAF"
425 public Result<Void> deleteNsAttrib(AuthzTrans trans, String ns, String key) {
426 TimeTaken tt = trans.start("Delete NsAttrib " + ns + ':' + key, Env.SUB);
429 final Validator v = new ServiceValidator();
430 if (v.nullOrBlank("NS",ns).err() ||
431 v.nullOrBlank("Key",key).err()) {
432 return Result.err(Status.ERR_BadData,v.errs());
435 // Check if exists already
436 Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
437 if (rlnsd.notOKorIsEmpty()) {
438 return Result.err(rlnsd);
440 NsDAO.Data nsd = rlnsd.value.get(0);
442 // Check for Existence
443 if (nsd.attrib.get(key)==null) {
444 return Result.err(Status.ERR_NotFound, "NS Property [%s:%s] does not exist", ns, key);
447 // Check if User may del
448 if (!ques.isGranted(trans, trans.user(), ROOT_NS, "attrib", ":" + ROOT_COMPANY + ".*:"+key, Access.write.name())) {
449 return Result.err(Status.ERR_Denied, "%s may not delete NS Attrib [%s:%s]", trans.user(),ns, key);
453 nsd.attrib.remove(key);
454 ques.nsDAO.dao().attribRemove(trans,ns,key);
463 path = "/authz/nss/:id",
464 params = { "id|string|true" },
466 errorCodes = { 404,406 },
468 "Lists the Admin(s), Responsible Party(s), Role(s), Permission(s)",
469 "Credential(s) and Expiration of Credential(s) in Namespace :id",
473 public Result<NSS> getNSbyName(AuthzTrans trans, String ns) {
474 final Validator v = new ServiceValidator();
475 if (v.nullOrBlank("NS", ns).err()) {
476 return Result.err(Status.ERR_BadData,v.errs());
479 Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, ns);
481 if (rlnd.isEmpty()) {
482 return Result.err(Status.ERR_NotFound, "No data found for %s",ns);
484 Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.read);
486 return Result.err(rnd);
490 Namespace namespace = new Namespace(rnd.value);
491 Result<List<String>> rd = func.getOwners(trans, namespace.name, false);
493 namespace.owner = rd.value;
495 rd = func.getAdmins(trans, namespace.name, false);
497 namespace.admin = rd.value;
500 NSS nss = mapper.newInstance(API.NSS);
501 return mapper.nss(trans, namespace, nss);
503 return Result.err(rlnd);
509 path = "/authz/nss/admin/:id",
510 params = { "id|string|true" },
512 errorCodes = { 403,404 },
513 text = { "Lists all Namespaces where Identity :id is an Admin",
514 "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)"
518 public Result<NSS> getNSbyAdmin(AuthzTrans trans, String user, boolean full) {
519 final Validator v = new ServiceValidator();
520 if (v.nullOrBlank("User", user).err()) {
521 return Result.err(Status.ERR_BadData, v.errs());
524 Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".admin", full);
526 return Result.err(rn);
529 return Result.err(Status.ERR_NotFound, "[%s] is not an admin for any namespaces",user);
531 NSS nss = mapper.newInstance(API.NSS);
532 // Note: "loadNamespace" already validates view of Namespace
533 return mapper.nss(trans, rn.value, nss);
538 path = "/authz/nss/either/:id",
539 params = { "id|string|true" },
541 errorCodes = { 403,404 },
542 text = { "Lists all Namespaces where Identity :id is either an Admin or an Owner",
543 "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)"
547 public Result<NSS> getNSbyEither(AuthzTrans trans, String user, boolean full) {
548 final Validator v = new ServiceValidator();
549 if (v.nullOrBlank("User", user).err()) {
550 return Result.err(Status.ERR_BadData, v.errs());
553 Result<Collection<Namespace>> rn = loadNamepace(trans, user, null, full);
555 return Result.err(rn);
558 return Result.err(Status.ERR_NotFound, "[%s] is not an admin or owner for any namespaces",user);
560 NSS nss = mapper.newInstance(API.NSS);
561 // Note: "loadNamespace" already validates view of Namespace
562 return mapper.nss(trans, rn.value, nss);
565 private Result<Collection<Namespace>> loadNamepace(AuthzTrans trans, String user, String endsWith, boolean full) {
566 Result<List<UserRoleDAO.Data>> urd = ques.userRoleDAO.readByUser(trans, user);
567 if (urd.notOKorIsEmpty()) {
568 return Result.err(urd);
570 Map<String, Namespace> lm = new HashMap<>();
571 Map<String, Namespace> other = full || endsWith==null?null:new TreeMap<>();
572 for (UserRoleDAO.Data urdd : urd.value) {
574 if (endsWith==null || urdd.role.endsWith(endsWith)) {
575 RoleDAO.Data rd = RoleDAO.Data.decode(urdd);
576 Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read);
578 Namespace namespace = lm.get(nsd.value.name);
579 if (namespace==null) {
580 namespace = new Namespace(nsd.value);
581 lm.put(namespace.name,namespace);
583 Result<List<String>> rls = func.getAdmins(trans, namespace.name, false);
585 namespace.admin=rls.value;
588 rls = func.getOwners(trans, namespace.name, false);
590 namespace.owner=rls.value;
594 } else { // Shortened version. Only Namespace Info available from Role.
595 if (Question.ADMIN.equals(urdd.rname) || Question.OWNER.equals(urdd.rname)) {
596 RoleDAO.Data rd = RoleDAO.Data.decode(urdd);
597 Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read);
599 Namespace namespace = lm.get(nsd.value.name);
600 if (namespace==null) {
602 namespace = other.remove(nsd.value.name);
604 if (namespace==null) {
605 namespace = new Namespace(nsd.value);
606 namespace.admin=new ArrayList<>();
607 namespace.owner=new ArrayList<>();
609 if (endsWith==null || urdd.role.endsWith(endsWith)) {
610 lm.put(namespace.name,namespace);
612 other.put(namespace.name,namespace);
615 if (Question.OWNER.equals(urdd.rname)) {
616 namespace.owner.add(urdd.user);
618 namespace.admin.add(urdd.user);
624 return Result.ok(lm.values());
629 path = "/authz/nss/responsible/:id",
630 params = { "id|string|true" },
632 errorCodes = { 403,404 },
633 text = { "Lists all Namespaces where Identity :id is a Responsible Party",
634 "Note: :id must be fully qualified (i.e. ab1234@people.osaaf.org)"
638 public Result<NSS> getNSbyResponsible(AuthzTrans trans, String user, boolean full) {
639 final Validator v = new ServiceValidator();
640 if (v.nullOrBlank("User", user).err()) {
641 return Result.err(Status.ERR_BadData, v.errs());
643 Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".owner",full);
645 return Result.err(rn);
648 return Result.err(Status.ERR_NotFound, "[%s] is not an owner for any namespaces",user);
650 NSS nss = mapper.newInstance(API.NSS);
651 // Note: "loadNamespace" prevalidates
652 return mapper.nss(trans, rn.value, nss);
657 path = "/authz/nss/children/:id",
658 params = { "id|string|true" },
660 errorCodes = { 403,404 },
661 text = { "Lists all Child Namespaces of Namespace :id",
662 "Note: This is not a cached read"
666 public Result<NSS> getNSsChildren(AuthzTrans trans, String parent) {
667 final Validator v = new ServiceValidator();
668 if (v.nullOrBlank("NS", parent).err()) {
669 return Result.err(Status.ERR_BadData,v.errs());
672 Result<NsDAO.Data> rnd = ques.deriveNs(trans, parent);
674 return Result.err(rnd);
676 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
678 return Result.err(rnd);
681 Set<Namespace> lm = new HashSet<>();
682 Result<List<NsDAO.Data>> rlnd = ques.nsDAO.dao().getChildren(trans, parent);
684 if (rlnd.isEmpty()) {
685 return Result.err(Status.ERR_NotFound, "No data found for %s",parent);
687 for (NsDAO.Data ndd : rlnd.value) {
688 Namespace namespace = new Namespace(ndd);
689 Result<List<String>> rls = func.getAdmins(trans, namespace.name, false);
691 namespace.admin=rls.value;
694 rls = func.getOwners(trans, namespace.name, false);
696 namespace.owner=rls.value;
701 NSS nss = mapper.newInstance(API.NSS);
702 return mapper.nss(trans,lm, nss);
704 return Result.err(rlnd);
714 errorCodes = { 403,404,406 },
715 text = { "Replace the Current Description of a Namespace with a new one"
719 public Result<Void> updateNsDescription(AuthzTrans trans, REQUEST from) {
720 final Result<Namespace> nsd = mapper.ns(trans, from);
721 final ServiceValidator v = new ServiceValidator();
722 if (v.ns(nsd).err()) {
723 return Result.err(Status.ERR_BadData,v.errs());
725 if (v.nullOrBlank("description", nsd.value.description).err()) {
726 return Result.err(Status.ERR_BadData,v.errs());
729 Namespace namespace = nsd.value;
730 Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, namespace.name);
732 if (rlnd.notOKorIsEmpty()) {
733 return Result.err(Status.ERR_NotFound, "Namespace [%s] does not exist",namespace.name);
736 if (ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.write).notOK()) {
737 return Result.err(Status.ERR_Denied, "You do not have approval to change %s",namespace.name);
740 Result<Void> rdr = ques.nsDAO.dao().addDescription(trans, namespace.name, namespace.description);
744 return Result.err(rdr);
750 * @throws DAOException
751 * @see org.onap.aaf.auth.service.AuthzService#deleteNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String)
755 path = "/authz/ns/:ns",
756 params = { "ns|string|true" },
758 errorCodes = { 403,404,424 },
759 text = { "Delete the Namespace :ns. Namespaces cannot normally be deleted when there ",
760 "are still credentials associated with them, but they can be deleted by setting ",
761 "the \"force\" property. To do this: Add 'force=true' as a query parameter",
762 "<p>WARNING: Using force will delete all credentials attached to this namespace. Use with care.</p>"
763 + "if the \"force\" property is set to 'force=move', then Permissions and Roles are not deleted,"
764 + "but are retained, and assigned to the Parent Namespace. 'force=move' is not permitted "
765 + "at or below Application Scope"
769 public Result<Void> deleteNS(AuthzTrans trans, String ns) {
770 return func.deleteNS(trans, ns);
774 /***********************************
776 ***********************************/
780 * @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)
784 path = "/authz/perm",
787 errorCodes = {403,404,406,409},
788 text = { "Permission consists of:",
789 "<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
790 + "is being protected</li>",
791 "<li>instance - a key, possibly multi-dimensional, that identifies a specific "
792 + " instance of the type</li>",
793 "<li>action - what kind of action is allowed</li></ul>",
794 "Note: instance and action can be an *"
798 public Result<Void> createPerm(final AuthzTrans trans,REQUEST rreq) {
799 final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq);
800 final ServiceValidator v = new ServiceValidator();
801 if (v.perm(newPd).err()) {
802 return Result.err(Status.ERR_BadData,v.errs());
805 Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, newPd.value,false,
808 public String get() {
809 return "Create Permission [" +
810 newPd.value.fullType() + '|' +
811 newPd.value.instance + '|' +
812 newPd.value.action + ']';
816 private Result<NsDAO.Data> nsd;
818 public Result<?> mayChange() {
820 nsd = ques.mayUser(trans, trans.user(), newPd.value, Access.write);
825 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, newPd.value.ns);
826 if (nsr.notOKorIsEmpty()) {
827 return Result.err(nsr);
831 Result<String> rfc = func.createFuture(trans,fd.value,
832 newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action,
837 return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
840 newPd.value.instance,
843 return Result.err(rfc);
846 return func.createPerm(trans, newPd.value, true);
848 return Result.err(fd);
854 path = "/authz/perms/:type",
855 params = {"type|string|true"},
857 errorCodes = { 404,406 },
858 text = { "List All Permissions that match the :type element of the key" }
861 public Result<PERMS> getPermsByType(AuthzTrans trans, final String permType) {
862 final Validator v = new ServiceValidator();
863 if (v.nullOrBlank("PermType", permType).err()) {
864 return Result.err(Status.ERR_BadData,v.errs());
867 Result<List<PermDAO.Data>> rlpd = ques.getPermsByType(trans, permType);
869 return Result.err(rlpd);
872 // We don't have instance & action for mayUserView... do we want to loop through all returned here as well as in mapper?
873 // Result<NsDAO.Data> r;
874 // if ((r = ques.mayUserViewPerm(trans, trans.user(), permType)).notOK())return Result.err(r);
876 PERMS perms = mapper.newInstance(API.PERMS);
877 if (!rlpd.isEmpty()) {
878 // Note: Mapper will restrict what can be viewed
879 return mapper.perms(trans, rlpd.value, perms, true);
881 return Result.ok(perms);
886 path = "/authz/perms/:type/:instance/:action",
887 params = {"type|string|true",
888 "instance|string|true",
889 "action|string|true"},
891 errorCodes = { 404,406 },
892 text = { "List Permissions that match key; :type, :instance and :action" }
895 public Result<PERMS> getPermsByName(AuthzTrans trans, String type, String instance, String action) {
896 final Validator v = new ServiceValidator();
897 if (v.nullOrBlank("PermType", type).err()
898 || v.nullOrBlank("PermInstance", instance).err()
899 || v.nullOrBlank("PermAction", action).err()) {
900 return Result.err(Status.ERR_BadData,v.errs());
903 Result<List<PermDAO.Data>> rlpd = ques.getPermsByName(trans, type, instance, action);
905 return Result.err(rlpd);
908 PERMS perms = mapper.newInstance(API.PERMS);
909 if (!rlpd.isEmpty()) {
910 // Note: Mapper will restrict what can be viewed
911 return mapper.perms(trans, rlpd.value, perms, true);
913 return Result.ok(perms);
918 path = "/authz/perms/user/:user",
919 params = {"user|string|true"},
921 errorCodes = { 404,406 },
922 text = { "List All Permissions that match user :user",
923 "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>"}
926 public Result<PERMS> getPermsByUser(AuthzTrans trans, String user) {
927 final Validator v = new ServiceValidator();
928 if (v.nullOrBlank("User", user).err()) {
929 return Result.err(Status.ERR_BadData,v.errs());
932 Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user,
933 trans.requested(force));
935 return Result.err(rlpd);
938 PERMS perms = mapper.newInstance(API.PERMS);
940 if (rlpd.isEmpty()) {
941 return Result.ok(perms);
943 // Note: Mapper will restrict what can be viewed
944 // if user is the same as that which is looked up, no filtering is required
945 return mapper.perms(trans, rlpd.value,
947 !user.equals(trans.user()));
952 path = "/authz/perms/user/:user/scope/:scope",
953 params = {"user|string|true","scope|string|true"},
955 errorCodes = { 404,406 },
956 text = { "List All Permissions that match user :user, filtered by NS (Scope)",
957 "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>",
958 "<p>'scope' must be expressed as NSs separated by ':'</p>"
962 public Result<PERMS> getPermsByUserScope(AuthzTrans trans, String user, String[] scopes) {
963 final Validator v = new ServiceValidator();
964 if (v.nullOrBlank("User", user).err()) {
965 return Result.err(Status.ERR_BadData,v.errs());
968 Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user, trans.requested(force));
970 return Result.err(rlpd);
973 PERMS perms = mapper.newInstance(API.PERMS);
975 if (rlpd.isEmpty()) {
976 return Result.ok(perms);
978 // Note: Mapper will restrict what can be viewed
979 // if user is the same as that which is looked up, no filtering is required
980 return mapper.perms(trans, rlpd.value,
983 !user.equals(trans.user()));
988 path = "/authz/perms/user/:user",
989 params = {"user|string|true"},
991 errorCodes = { 404,406 },
992 text = { "List All Permissions that match user :user",
993 "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>",
995 "Present Queries as one or more Permissions (see ContentType Links below for format).",
997 "If the Caller is Granted this specific Permission, and the Permission is valid",
998 " for the User, it will be included in response Permissions, along with",
999 " all the normal permissions on the 'GET' version of this call. If it is not",
1000 " valid, or Caller does not have permission to see, it will be removed from the list",
1002 " *Note: This design allows you to make one call for all expected permissions",
1003 " The permission to be included MUST be:",
1004 " <user namespace>.access|:<ns|role|perm>[:key]|<create|read|write>",
1006 " com.att.myns.access|:ns|write",
1007 " com.att.myns.access|:role:myrole|create",
1008 " com.att.myns.access|:perm:mytype:myinstance:myaction|read",
1013 public Result<PERMS> getPermsByUser(AuthzTrans trans, PERMS _perms, String user) {
1014 PERMS perms = _perms;
1015 final Validator v = new ServiceValidator();
1016 if (v.nullOrBlank("User", user).err()) {
1017 return Result.err(Status.ERR_BadData,v.errs());
1021 Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user,trans.requested(force));
1023 return Result.err(rlpd);
1027 1) See if allowed to query
1028 2) See if User is allowed
1030 Result<List<PermDAO.Data>> in = mapper.perms(trans, perms);
1031 if (in.isOKhasData()) {
1032 List<PermDAO.Data> out = rlpd.value;
1034 for (PermDAO.Data pdd : in.value) {
1036 if ("access".equals(pdd.type)) {
1037 Access access = Access.valueOf(pdd.action);
1038 String[] mdkey = Split.splitTrim(':',pdd.instance);
1039 if (mdkey.length>1) {
1040 String type = mdkey[1];
1041 if ("role".equals(type)) {
1042 if (mdkey.length>2) {
1043 RoleDAO.Data rdd = new RoleDAO.Data();
1046 ok = ques.mayUser(trans, trans.user(), rdd, Access.read).isOK() && ques.mayUser(trans, user, rdd , access).isOK();
1048 } else if ("perm".equals(type)) {
1049 if (mdkey.length>4) { // also need instance/action
1050 PermDAO.Data p = new PermDAO.Data();
1053 p.instance=mdkey[3];
1055 ok = ques.mayUser(trans, trans.user(), p, Access.read).isOK() && ques.mayUser(trans, user, p , access).isOK();
1057 } else if ("ns".equals(type)) {
1058 NsDAO.Data ndd = new NsDAO.Data();
1060 ok = ques.mayUser(trans, trans.user(), ndd, Access.read).isOK() && ques.mayUser(trans, user, ndd , access).isOK();
1070 perms = mapper.newInstance(API.PERMS);
1071 if (rlpd.isEmpty()) {
1072 return Result.ok(perms);
1074 // Note: Mapper will restrict what can be viewed
1075 // if user is the same as that which is looked up, no filtering is required
1076 return mapper.perms(trans, rlpd.value,
1078 !user.equals(trans.user()));
1083 path = "/authz/perms/role/:role",
1084 params = {"role|string|true"},
1086 errorCodes = { 404,406 },
1087 text = { "List All Permissions that are granted to :role" }
1090 public Result<PERMS> getPermsByRole(AuthzTrans trans,String role) {
1091 final Validator v = new ServiceValidator();
1092 if (v.nullOrBlank("Role", role).err()) {
1093 return Result.err(Status.ERR_BadData,v.errs());
1096 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques,role);
1098 return Result.err(rrdd);
1101 Result<NsDAO.Data> r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read);
1103 return Result.err(r);
1106 PERMS perms = mapper.newInstance(API.PERMS);
1108 Result<List<PermDAO.Data>> rlpd = ques.getPermsByRole(trans, role, trans.requested(force));
1109 if (rlpd.isOKhasData()) {
1110 // Note: Mapper will restrict what can be viewed
1111 return mapper.perms(trans, rlpd.value, perms, true);
1113 return Result.ok(perms);
1118 path = "/authz/perms/ns/:ns",
1119 params = {"ns|string|true"},
1121 errorCodes = { 404,406 },
1122 text = { "List All Permissions that are in Namespace :ns" }
1125 public Result<PERMS> getPermsByNS(AuthzTrans trans,String ns) {
1126 final Validator v = new ServiceValidator();
1127 if (v.nullOrBlank("NS", ns).err()) {
1128 return Result.err(Status.ERR_BadData,v.errs());
1131 Result<NsDAO.Data> rnd = ques.deriveNs(trans, ns);
1133 return Result.err(rnd);
1136 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
1138 return Result.err(rnd);
1141 Result<List<PermDAO.Data>> rlpd = ques.permDAO.readNS(trans, ns);
1143 return Result.err(rlpd);
1146 PERMS perms = mapper.newInstance(API.PERMS);
1147 if (!rlpd.isEmpty()) {
1148 // Note: Mapper will restrict what can be viewed
1149 return mapper.perms(trans, rlpd.value,perms, true);
1151 return Result.ok(perms);
1156 path = "/authz/perm/:type/:instance/:action",
1157 params = {"type|string|true",
1158 "instance|string|true",
1159 "action|string|true"},
1161 errorCodes = { 404,406, 409 },
1162 text = { "Rename the Permission referenced by :type :instance :action, and "
1163 + "rename (copy/delete) to the Permission described in PermRequest" }
1166 public Result<Void> renamePerm(final AuthzTrans trans,REQUEST rreq, String origType, String origInstance, String origAction) {
1167 final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq);
1168 final ServiceValidator v = new ServiceValidator();
1169 if (v.perm(newPd).err()) {
1170 return Result.err(Status.ERR_BadData,v.errs());
1173 if (ques.mayUser(trans, trans.user(), newPd.value,Access.write).notOK()) {
1174 return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]",
1175 newPd.value.ns,newPd.value.type,newPd.value.instance,newPd.value.action);
1178 Result<NsSplit> nss = ques.deriveNsSplit(trans, origType);
1179 Result<List<PermDAO.Data>> origRlpd = ques.permDAO.read(trans, nss.value.ns, nss.value.name, origInstance, origAction);
1181 if (origRlpd.notOKorIsEmpty()) {
1182 return Result.err(Status.ERR_PermissionNotFound,
1183 "Permission [%s|%s|%s] does not exist",
1184 origType,origInstance,origAction);
1187 PermDAO.Data origPd = origRlpd.value.get(0);
1189 if (!origPd.ns.equals(newPd.value.ns)) {
1190 return Result.err(Status.ERR_Denied, "Cannot change namespace with rename command. " +
1191 "<new type> must start with [" + origPd.ns + "]");
1194 if ( origPd.type.equals(newPd.value.type) &&
1195 origPd.action.equals(newPd.value.action) &&
1196 origPd.instance.equals(newPd.value.instance) ) {
1197 return Result.err(Status.ERR_ConflictAlreadyExists, "New Permission must be different than original permission");
1200 Set<String> origRoles = origPd.roles(false);
1201 if (!origRoles.isEmpty()) {
1202 Set<String> roles = newPd.value.roles(true);
1203 for (String role : origPd.roles) {
1208 newPd.value.description = origPd.description;
1210 Result<Void> rv = null;
1212 rv = func.createPerm(trans, newPd.value, false);
1214 rv = func.deletePerm(trans, origPd, true, false);
1221 path = "/authz/perm",
1224 errorCodes = { 404,406 },
1225 text = { "Add Description Data to Perm" }
1228 public Result<Void> updatePermDescription(AuthzTrans trans, REQUEST from) {
1229 final Result<PermDAO.Data> pd = mapper.perm(trans, from);
1230 final ServiceValidator v = new ServiceValidator();
1231 if (v.perm(pd).err()) {
1232 return Result.err(Status.ERR_BadData,v.errs());
1234 if (v.nullOrBlank("description", pd.value.description).err()) {
1235 return Result.err(Status.ERR_BadData,v.errs());
1237 final PermDAO.Data perm = pd.value;
1238 if (ques.permDAO.read(trans, perm.ns, perm.type, perm.instance,perm.action).notOKorIsEmpty()) {
1239 return Result.err(Status.ERR_NotFound, "Permission [%s.%s|%s|%s] does not exist",
1240 perm.ns,perm.type,perm.instance,perm.action);
1243 if (ques.mayUser(trans, trans.user(), perm, Access.write).notOK()) {
1244 return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]",
1245 perm.ns,perm.type,perm.instance,perm.action);
1248 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pd.value.ns);
1249 if (nsr.notOKorIsEmpty()) {
1250 return Result.err(nsr);
1253 Result<Void> rdr = ques.permDAO.addDescription(trans, perm.ns, perm.type, perm.instance,
1254 perm.action, perm.description);
1258 return Result.err(rdr);
1265 path = "/authz/role/perm",
1268 errorCodes = {403,404,406,409},
1269 text = { "Set a permission's roles to roles given" }
1273 public Result<Void> resetPermRoles(final AuthzTrans trans, REQUEST rreq) {
1274 final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq);
1275 if (updt.notOKorIsEmpty()) {
1276 return Result.err(updt);
1279 final ServiceValidator v = new ServiceValidator();
1280 if (v.perm(updt).err()) {
1281 return Result.err(Status.ERR_BadData,v.errs());
1284 Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write);
1286 return Result.err(nsd);
1289 // Read full set to get CURRENT values
1290 Result<List<PermDAO.Data>> rcurr = ques.permDAO.read(trans,
1293 updt.value.instance,
1296 if (rcurr.notOKorIsEmpty()) {
1297 return Result.err(Status.ERR_PermissionNotFound,
1298 "Permission [%s.%s|%s|%s] does not exist",
1299 updt.value.ns,updt.value.type,updt.value.instance,updt.value.action);
1302 // Create a set of Update Roles, which are in Internal Format
1303 Set<String> updtRoles = new HashSet<>();
1304 Result<NsSplit> nss;
1305 for (String role : updt.value.roles(false)) {
1306 nss = ques.deriveNsSplit(trans, role);
1308 updtRoles.add(nss.value.ns + '|' + nss.value.name);
1310 trans.error().log(nss.errorString());
1314 Result<Void> rv = null;
1316 for (PermDAO.Data curr : rcurr.value) {
1317 Set<String> currRoles = curr.roles(false);
1318 // must add roles to this perm, and add this perm to each role
1319 // in the update, but not in the current
1320 for (String role : updtRoles) {
1321 if (!currRoles.contains(role)) {
1322 Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role);
1323 if (key.isOKhasData()) {
1324 Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, key.value);
1325 if (rrd.isOKhasData()) {
1326 for (RoleDAO.Data r : rrd.value) {
1327 rv = func.addPermToRole(trans, r, curr, false);
1328 if (rv.notOK() && rv.status!=Result.ERR_ConflictAlreadyExists) {
1329 return Result.err(rv);
1333 return Result.err(rrd);
1338 // similarly, must delete roles from this perm, and delete this perm from each role
1339 // in the update, but not in the current
1340 for (String role : currRoles) {
1341 if (!updtRoles.contains(role)) {
1342 Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role);
1343 if (key.isOKhasData()) {
1344 Result<List<RoleDAO.Data>> rdd = ques.roleDAO.read(trans, key.value);
1345 if (rdd.isOKhasData()) {
1346 for (RoleDAO.Data r : rdd.value) {
1347 rv = func.delPermFromRole(trans, r, curr, true);
1348 if (rv.notOK() && rv.status!=Status.ERR_PermissionNotFound) {
1349 return Result.err(rv);
1357 return rv==null?Result.ok():rv;
1362 path = "/authz/perm",
1365 errorCodes = { 404,406 },
1366 text = { "Delete the Permission referenced by PermKey.",
1367 "You cannot normally delete a permission which is still granted to roles,",
1368 "however the \"force\" property allows you to do just that. To do this: Add",
1369 "'force=true' as a query parameter.",
1370 "<p>WARNING: Using force will ungrant this permission from all roles. Use with care.</p>" }
1373 public Result<Void> deletePerm(final AuthzTrans trans, REQUEST from) {
1374 Result<PermDAO.Data> pd = mapper.perm(trans, from);
1376 return Result.err(pd);
1378 final ServiceValidator v = new ServiceValidator();
1379 if (v.nullOrBlank(pd.value).err()) {
1380 return Result.err(Status.ERR_BadData,v.errs());
1382 final PermDAO.Data perm = pd.value;
1383 if (ques.permDAO.read(trans, perm).notOKorIsEmpty()) {
1384 return Result.err(Status.ERR_PermissionNotFound, "Permission [%s.%s|%s|%s] does not exist",
1385 perm.ns,perm.type,perm.instance,perm.action );
1388 Result<FutureDAO.Data> fd = mapper.future(trans,PermDAO.TABLE,from,perm,false,
1391 public String get() {
1392 return "Delete Permission [" + perm.fullPerm() + ']';
1396 private Result<NsDAO.Data> nsd;
1398 public Result<?> mayChange() {
1400 nsd = ques.mayUser(trans, trans.user(), perm, Access.write);
1408 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, perm.ns);
1409 if (nsr.notOKorIsEmpty()) {
1410 return Result.err(nsr);
1413 Result<String> rfc = func.createFuture(trans, fd.value,
1414 perm.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D);
1416 return Result.err(Status.ACC_Future, "Perm Deletion [%s] is saved for future processing",perm.encode());
1418 return Result.err(rfc);
1420 case Status.ACC_Now:
1421 return func.deletePerm(trans,perm,trans.requested(force), false);
1423 return Result.err(fd);
1429 path = "/authz/perm/:name/:type/:action",
1430 params = {"type|string|true",
1431 "instance|string|true",
1432 "action|string|true"},
1434 errorCodes = { 404,406 },
1435 text = { "Delete the Permission referenced by :type :instance :action",
1436 "You cannot normally delete a permission which is still granted to roles,",
1437 "however the \"force\" property allows you to do just that. To do this: Add",
1438 "'force=true' as a query parameter",
1439 "<p>WARNING: Using force will ungrant this permission from all roles. Use with care.</p>"}
1442 public Result<Void> deletePerm(AuthzTrans trans, String type, String instance, String action) {
1443 final Validator v = new ServiceValidator();
1444 if (v.nullOrBlank("Type",type)
1445 .nullOrBlank("Instance",instance)
1446 .nullOrBlank("Action",action)
1448 return Result.err(Status.ERR_BadData,v.errs());
1451 Result<PermDAO.Data> pd = ques.permFrom(trans, type, instance, action);
1453 return func.deletePerm(trans, pd.value, trans.requested(force), false);
1455 return Result.err(pd);
1459 /***********************************
1461 ***********************************/
1464 path = "/authz/role",
1467 errorCodes = {403,404,406,409},
1470 "Roles are part of Namespaces",
1472 "<ul><li>org.onap.aaf - The team that created and maintains AAF</li>",
1473 "Roles do not include implied permissions for an App. Instead, they contain explicit Granted Permissions by any Namespace in AAF (See Permissions)",
1474 "Restrictions on Role Names:",
1475 "<ul><li>Must start with valid Namespace name, terminated by . (dot/period)</li>",
1476 "<li>Allowed Characters are a-zA-Z0-9._-</li>",
1477 "<li>role names are Case Sensitive</li></ul>",
1478 "The right questions to ask for defining and populating a Role in AAF, therefore, are:",
1479 "<ul><li>'What Job Function does this represent?'</li>",
1480 "<li>'Does this person perform this Job Function?'</li></ul>" }
1484 public Result<Void> createRole(final AuthzTrans trans, REQUEST from) {
1485 final Result<RoleDAO.Data> rd = mapper.role(trans, from);
1486 final ServiceValidator v = new ServiceValidator();
1487 if (v.role(rd).err()) {
1488 return Result.err(Status.ERR_BadData,v.errs());
1490 final RoleDAO.Data role = rd.value;
1491 if (ques.roleDAO.read(trans, role.ns, role.name).isOKhasData()) {
1492 return Result.err(Status.ERR_ConflictAlreadyExists, "Role [" + role.fullName() + "] already exists");
1495 Result<FutureDAO.Data> fd = mapper.future(trans,RoleDAO.TABLE,from,role,false,
1498 public String get() {
1499 return "Create Role [" +
1500 rd.value.fullName() +
1505 private Result<NsDAO.Data> nsd;
1507 public Result<?> mayChange() {
1509 nsd = ques.mayUser(trans, trans.user(), role, Access.write);
1515 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
1516 if (nsr.notOKorIsEmpty()) {
1517 return Result.err(nsr);
1522 Result<String> rfc = func.createFuture(trans, fd.value,
1523 role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.C);
1525 return Result.err(Status.ACC_Future, "Role [%s.%s] is saved for future processing",
1529 return Result.err(rfc);
1531 case Status.ACC_Now:
1532 Result<RoleDAO.Data> rdr = ques.roleDAO.create(trans, role);
1536 return Result.err(rdr);
1539 return Result.err(fd);
1544 * @see org.onap.aaf.auth.service.AuthzService#getRolesByName(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
1548 path = "/authz/roles/:role",
1549 params = {"role|string|true"},
1551 errorCodes = {404,406},
1552 text = { "List Roles that match :role",
1553 "Note: You must have permission to see any given role"
1557 public Result<ROLES> getRolesByName(AuthzTrans trans, String role) {
1558 final Validator v = new ServiceValidator();
1559 if (v.nullOrBlank("Role", role).err()) {
1560 return Result.err(Status.ERR_BadData,v.errs());
1563 // Determine if User can ask this question
1564 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
1565 if (rrdd.isOKhasData()) {
1566 Result<NsDAO.Data> r;
1567 if ((r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read)).notOK()) {
1568 return Result.err(r);
1571 return Result.err(rrdd);
1575 int query = role.indexOf('?');
1576 Result<List<RoleDAO.Data>> rlrd = ques.getRolesByName(trans, query<0?role:role.substring(0, query));
1578 // Note: Mapper will restrict what can be viewed
1579 ROLES roles = mapper.newInstance(API.ROLES);
1580 return mapper.roles(trans, rlrd.value, roles, true);
1582 return Result.err(rlrd);
1587 * @see org.onap.aaf.auth.service.AuthzService#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
1591 path = "/authz/roles/user/:name",
1592 params = {"name|string|true"},
1594 errorCodes = {404,406},
1595 text = { "List all Roles that match user :name",
1596 "'user' must be expressed as full identity (ex: id@full.domain.com)",
1597 "Note: You must have permission to see any given role"
1602 public Result<ROLES> getRolesByUser(AuthzTrans trans, String user) {
1603 final Validator v = new ServiceValidator();
1604 if (v.nullOrBlank("User", user).err()) {
1605 return Result.err(Status.ERR_BadData,v.errs());
1608 ROLES roles = mapper.newInstance(API.ROLES);
1609 // Get list of roles per user, then add to Roles as we go
1610 Result<List<RoleDAO.Data>> rlrd;
1611 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user);
1612 if (rlurd.isOKhasData()) {
1613 for (UserRoleDAO.Data urd : rlurd.value ) {
1614 rlrd = ques.roleDAO.read(trans, urd.ns,urd.rname);
1615 // Note: Mapper will restrict what can be viewed
1616 // if user is the same as that which is looked up, no filtering is required
1617 if (rlrd.isOKhasData()) {
1618 mapper.roles(trans, rlrd.value,roles, !user.equals(trans.user()));
1622 return Result.ok(roles);
1627 * @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
1631 path = "/authz/roles/ns/:ns",
1632 params = {"ns|string|true"},
1634 errorCodes = {404,406},
1635 text = { "List all Roles for the Namespace :ns",
1636 "Note: You must have permission to see any given role"
1641 public Result<ROLES> getRolesByNS(AuthzTrans trans, String ns) {
1642 final Validator v = new ServiceValidator();
1643 if (v.nullOrBlank("NS", ns).err()) {
1644 return Result.err(Status.ERR_BadData,v.errs());
1647 // check if user is allowed to view NS
1648 Result<NsDAO.Data> rnsd = ques.deriveNs(trans, ns);
1650 return Result.err(rnsd);
1652 rnsd = ques.mayUser(trans, trans.user(), rnsd.value, Access.read);
1654 return Result.err(rnsd);
1657 TimeTaken tt = trans.start("MAP Roles by NS to Roles", Env.SUB);
1659 ROLES roles = mapper.newInstance(API.ROLES);
1660 // Get list of roles per user, then add to Roles as we go
1661 Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readNS(trans, ns);
1663 if (!rlrd.isEmpty()) {
1664 // Note: Mapper doesn't need to restrict what can be viewed, because we did it already.
1665 mapper.roles(trans,rlrd.value,roles,false);
1667 return Result.ok(roles);
1669 return Result.err(rlrd);
1678 * @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
1682 path = "/authz/roles/name/:name",
1683 params = {"name|string|true"},
1685 errorCodes = {404,406},
1686 text = { "List all Roles for only the Name of Role (without Namespace)",
1687 "Note: You must have permission to see any given role"
1691 public Result<ROLES> getRolesByNameOnly(AuthzTrans trans, String name) {
1692 final Validator v = new ServiceValidator();
1693 if (v.nullOrBlank("Name", name).err()) {
1694 return Result.err(Status.ERR_BadData,v.errs());
1697 // User Mapper to make sure user is allowed to view NS
1699 TimeTaken tt = trans.start("MAP Roles by Name to Roles", Env.SUB);
1701 ROLES roles = mapper.newInstance(API.ROLES);
1702 // Get list of roles per user, then add to Roles as we go
1703 Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readName(trans, name);
1705 if (!rlrd.isEmpty()) {
1706 // Note: Mapper will restrict what can be viewed
1707 mapper.roles(trans,rlrd.value,roles,true);
1709 return Result.ok(roles);
1711 return Result.err(rlrd);
1720 path = "/authz/roles/perm/:type/:instance/:action",
1721 params = {"type|string|true",
1722 "instance|string|true",
1723 "action|string|true"},
1725 errorCodes = {404,406},
1726 text = { "Find all Roles containing the given Permission." +
1727 "Permission consists of:",
1728 "<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
1729 + "is being protected</li>",
1730 "<li>instance - a key, possibly multi-dimensional, that identifies a specific "
1731 + " instance of the type</li>",
1732 "<li>action - what kind of action is allowed</li></ul>",
1733 "Notes: instance and action can be an *",
1734 " You must have permission to see any given role"
1739 public Result<ROLES> getRolesByPerm(AuthzTrans trans, String type, String instance, String action) {
1740 final Validator v = new ServiceValidator();
1741 if (v.permType(type)
1742 .permInstance(instance)
1745 return Result.err(Status.ERR_BadData,v.errs());
1748 TimeTaken tt = trans.start("Map Perm Roles Roles", Env.SUB);
1750 ROLES roles = mapper.newInstance(API.ROLES);
1751 // Get list of roles per user, then add to Roles as we go
1752 Result<NsSplit> nsSplit = ques.deriveNsSplit(trans, type);
1753 if (nsSplit.isOK()) {
1754 PermDAO.Data pdd = new PermDAO.Data(nsSplit.value, instance, action);
1756 if ((res=ques.mayUser(trans, trans.user(), pdd, Question.Access.read)).notOK()) {
1757 return Result.err(res);
1760 Result<List<PermDAO.Data>> pdlr = ques.permDAO.read(trans, pdd);
1761 if (pdlr.isOK())for (PermDAO.Data pd : pdlr.value) {
1762 Result<List<RoleDAO.Data>> rlrd;
1763 for (String r : pd.roles) {
1764 Result<String[]> rs = RoleDAO.Data.decodeToArray(trans, ques, r);
1766 rlrd = ques.roleDAO.read(trans, rs.value[0],rs.value[1]);
1767 // Note: Mapper will restrict what can be viewed
1768 if (rlrd.isOKhasData()) {
1769 mapper.roles(trans,rlrd.value,roles,true);
1775 return Result.ok(roles);
1783 path = "/authz/role",
1786 errorCodes = {404,406},
1787 text = { "Add Description Data to a Role" }
1791 public Result<Void> updateRoleDescription(AuthzTrans trans, REQUEST from) {
1792 final Result<RoleDAO.Data> rd = mapper.role(trans, from);
1793 final ServiceValidator v = new ServiceValidator();
1794 if (v.role(rd).err()) {
1795 return Result.err(Status.ERR_BadData,v.errs());
1797 if (v.nullOrBlank("description", rd.value.description).err()) {
1798 return Result.err(Status.ERR_BadData,v.errs());
1801 final RoleDAO.Data role = rd.value;
1802 if (ques.roleDAO.read(trans, role.ns, role.name).notOKorIsEmpty()) {
1803 return Result.err(Status.ERR_NotFound, "Role [" + role.fullName() + "] does not exist");
1806 if (ques.mayUser(trans, trans.user(), role, Access.write).notOK()) {
1807 return Result.err(Status.ERR_Denied, "You do not have approval to change " + role.fullName());
1810 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
1811 if (nsr.notOKorIsEmpty()) {
1812 return Result.err(nsr);
1815 Result<Void> rdr = ques.roleDAO.addDescription(trans, role.ns, role.name, role.description);
1819 return Result.err(rdr);
1826 path = "/authz/role/perm",
1829 errorCodes = {403,404,406,409},
1830 text = { "Grant a Permission to a Role",
1831 "Permission consists of:",
1832 "<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
1833 + "is being protected</li>",
1834 "<li>instance - a key, possibly multi-dimensional, that identifies a specific "
1835 + " instance of the type</li>",
1836 "<li>action - what kind of action is allowed</li></ul>",
1837 "Note: instance and action can be an *",
1838 "Note: Using the \"force\" property will create the Permission, if it doesn't exist AND the requesting " +
1839 " ID is allowed to create. It will then grant",
1840 " the permission to the role in one step. To do this: add 'force=true' as a query parameter."
1845 public Result<Void> addPermToRole(final AuthzTrans trans, REQUEST rreq) {
1846 // Translate Request into Perm and Role Objects
1847 final Result<PermDAO.Data> rpd = mapper.permFromRPRequest(trans, rreq);
1848 if (rpd.notOKorIsEmpty()) {
1849 return Result.err(rpd);
1851 final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq);
1852 if (rrd.notOKorIsEmpty()) {
1853 return Result.err(rrd);
1856 // Validate Role and Perm values
1857 final ServiceValidator v = new ServiceValidator();
1858 if (v.perm(rpd.value)
1861 return Result.err(Status.ERR_BadData,v.errs());
1864 Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.read(trans, rrd.value.ns, rrd.value.name);
1865 if (rlrd.notOKorIsEmpty()) {
1866 return Result.err(Status.ERR_RoleNotFound, "Role [%s] does not exist", rrd.value.fullName());
1869 // Check Status of Data in DB (does it exist)
1870 Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, rpd.value.ns,
1871 rpd.value.type, rpd.value.instance, rpd.value.action);
1872 PermDAO.Data createPerm = null; // if not null, create first
1873 if (rlpd.notOKorIsEmpty()) { // Permission doesn't exist
1874 if (trans.requested(force)) {
1875 // Remove roles from perm data object so we just create the perm here
1876 createPerm = rpd.value;
1877 createPerm.roles.clear();
1879 return Result.err(Status.ERR_PermissionNotFound,"Permission [%s.%s|%s|%s] does not exist",
1880 rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action);
1883 if (rlpd.value.get(0).roles(false).contains(rrd.value.encode())) {
1884 return Result.err(Status.ERR_ConflictAlreadyExists,
1885 "Permission [%s.%s|%s|%s] already granted to Role [%s.%s]",
1886 rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action,
1887 rrd.value.ns,rrd.value.name
1893 Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, rpd.value,true, // Allow grants to create Approvals
1896 public String get() {
1897 return "Grant Permission [" + rpd.value.fullPerm() + ']' +
1898 " to Role [" + rrd.value.fullName() + "]";
1902 private Result<NsDAO.Data> nsd;
1904 public Result<?> mayChange() {
1906 nsd = ques.mayUser(trans, trans.user(), rpd.value, Access.write);
1911 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rpd.value.ns);
1912 if (nsr.notOKorIsEmpty()) {
1913 return Result.err(nsr);
1917 Result<String> rfc = func.createFuture(trans,fd.value,
1918 rpd.value.fullPerm(),
1923 return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
1929 return Result.err(rfc);
1931 case Status.ACC_Now:
1932 Result<Void> rv = null;
1933 if (createPerm!=null) {// has been validated for creating
1934 rv = func.createPerm(trans, createPerm, false);
1936 if (rv==null || rv.isOK()) {
1937 rv = func.addPermToRole(trans, rrd.value, rpd.value, false);
1941 return Result.err(fd);
1947 * Delete Perms from Roles (UnGrant)
1949 * @param roleFullName
1954 path = "/authz/role/:role/perm",
1955 params = {"role|string|true"},
1957 errorCodes = {404,406},
1958 text = { "Ungrant a permission from Role :role" }
1962 public Result<Void> delPermFromRole(final AuthzTrans trans, REQUEST rreq) {
1963 final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq);
1964 if (updt.notOKorIsEmpty()) {
1965 return Result.err(updt);
1967 final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq);
1968 if (rrd.notOKorIsEmpty()) {
1969 return Result.err(rrd);
1972 final ServiceValidator v = new ServiceValidator();
1973 if (v.nullOrBlank(updt.value)
1974 .nullOrBlank(rrd.value)
1976 return Result.err(Status.ERR_BadData,v.errs());
1979 return delPermFromRole(trans, updt.value,rrd.value, rreq);
1982 private Result<Void> delPermFromRole(final AuthzTrans trans, PermDAO.Data pdd, RoleDAO.Data rdd, REQUEST rreq) {
1983 Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, pdd.ns, pdd.type,
1984 pdd.instance, pdd.action);
1986 if (rlpd.notOKorIsEmpty()) {
1987 return Result.err(Status.ERR_PermissionNotFound,
1988 "Permission [%s.%s|%s|%s] does not exist",
1989 pdd.ns,pdd.type,pdd.instance,pdd.action);
1992 Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, pdd,true, // allow ungrants requests
1995 public String get() {
1996 return "Ungrant Permission [" + pdd.fullPerm() + ']' +
1997 " from Role [" + rdd.fullName() + "]";
2001 private Result<NsDAO.Data> nsd;
2003 public Result<?> mayChange() {
2005 nsd = ques.mayUser(trans, trans.user(), pdd, Access.write);
2010 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pdd.ns);
2011 if (nsr.notOKorIsEmpty()) {
2012 return Result.err(nsr);
2016 Result<String> rfc = func.createFuture(trans,fd.value,
2023 return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
2029 return Result.err(rfc);
2031 case Status.ACC_Now:
2032 return func.delPermFromRole(trans, rdd, pdd, false);
2034 return Result.err(fd);
2041 path = "/authz/role/:role/perm/:type/:instance/:action",
2042 params = {"role|string|true",
2043 "perm type|string|true",
2044 "perm instance|string|true",
2045 "perm action|string|true"
2048 errorCodes = {404,406},
2049 text = { "Ungrant a single permission from Role :role with direct key" }
2053 public Result<Void> delPermFromRole(AuthzTrans trans, String role, String type, String instance, String action) {
2054 Result<Data> rpns = ques.deriveNs(trans, type);
2055 if (rpns.notOKorIsEmpty()) {
2056 return Result.err(rpns);
2059 final Validator v = new ServiceValidator();
2061 .permType(rpns.value.name,rpns.value.parent)
2062 .permInstance(instance)
2065 return Result.err(Status.ERR_BadData,v.errs());
2068 Result<Data> rrns = ques.deriveNs(trans, role);
2069 if (rrns.notOKorIsEmpty()) {
2070 return Result.err(rrns);
2073 final Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, rrns.value.parent, rrns.value.name);
2074 if (rrd.notOKorIsEmpty()) {
2075 return Result.err(rrd);
2078 final Result<List<PermDAO.Data>> rpd = ques.permDAO.read(trans, rpns.value.parent, rpns.value.name, instance, action);
2079 if (rpd.notOKorIsEmpty()) {
2080 return Result.err(rpd);
2084 return delPermFromRole(trans,rpd.value.get(0), rrd.value.get(0), mapper.ungrantRequest(trans, role, type, instance, action));
2089 path = "/authz/role/:role",
2090 params = {"role|string|true"},
2092 errorCodes = {404,406},
2093 text = { "Delete the Role named :role"}
2097 public Result<Void> deleteRole(AuthzTrans trans, String role) {
2098 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
2099 if (rrdd.isOKhasData()) {
2100 final ServiceValidator v = new ServiceValidator();
2101 if (v.nullOrBlank(rrdd.value).err()) {
2102 return Result.err(Status.ERR_BadData,v.errs());
2104 return func.deleteRole(trans, rrdd.value, false, false);
2106 return Result.err(rrdd);
2112 path = "/authz/role",
2115 errorCodes = { 404,406 },
2116 text = { "Delete the Role referenced by RoleKey",
2117 "You cannot normally delete a role which still has permissions granted or users assigned to it,",
2118 "however the \"force\" property allows you to do just that. To do this: Add 'force=true'",
2119 "as a query parameter.",
2120 "<p>WARNING: Using force will remove all users and permission from this role. Use with care.</p>"}
2124 public Result<Void> deleteRole(final AuthzTrans trans, REQUEST from) {
2125 final Result<RoleDAO.Data> rd = mapper.role(trans, from);
2126 final ServiceValidator v = new ServiceValidator();
2128 return Result.err(Status.ERR_BadData,"Request does not contain Role");
2130 if (v.nullOrBlank(rd.value).err()) {
2131 return Result.err(Status.ERR_BadData,v.errs());
2133 final RoleDAO.Data role = rd.value;
2134 if (ques.roleDAO.read(trans, role).notOKorIsEmpty() && !trans.requested(force)) {
2135 return Result.err(Status.ERR_RoleNotFound, "Role [" + role.fullName() + "] does not exist");
2138 Result<FutureDAO.Data> fd = mapper.future(trans,RoleDAO.TABLE,from,role,false,
2139 () -> "Delete Role [" + role.fullName() + ']'
2140 + " and all attached user roles",
2142 private Result<NsDAO.Data> nsd;
2144 public Result<?> mayChange() {
2146 nsd = ques.mayUser(trans, trans.user(), role, Access.write);
2154 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
2155 if (nsr.notOKorIsEmpty()) {
2156 return Result.err(nsr);
2159 Result<String> rfc = func.createFuture(trans, fd.value,
2160 role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D);
2162 return Result.err(Status.ACC_Future, "Role Deletion [%s.%s] is saved for future processing",
2166 return Result.err(rfc);
2168 case Status.ACC_Now:
2169 return func.deleteRole(trans,role,trans.requested(force), true /*preapproved*/);
2171 return Result.err(fd);
2176 /***********************************
2178 ***********************************/
2179 private class MayCreateCred implements MayChange {
2180 private Result<NsDAO.Data> nsd;
2181 private AuthzTrans trans;
2182 private CredDAO.Data cred;
2183 private Executor exec;
2185 public MayCreateCred(AuthzTrans trans, CredDAO.Data cred, Executor exec) {
2192 public Result<?> mayChange() {
2194 nsd = ques.validNSOfDomain(trans, cred.id);
2196 // is Ns of CredID valid?
2200 if (trans.org().validate(trans,Policy.CREATE_MECHID, exec, cred.id)==null) {
2203 Result<?> rmc = ques.mayUser(trans, trans.user(), nsd.value, Access.write);
2204 if (rmc.isOKhasData()) {
2208 } catch (Exception e) {
2209 trans.warn().log(e);
2212 trans.warn().log(nsd.errorString());
2214 return Result.err(Status.ERR_Denied,"%s is not allowed to create %s in %s",trans.user(),cred.id,cred.ns);
2218 private class MayChangeCred implements MayChange {
2220 private Result<NsDAO.Data> nsd;
2221 private AuthzTrans trans;
2222 private CredDAO.Data cred;
2223 public MayChangeCred(AuthzTrans trans, CredDAO.Data cred) {
2229 public Result<?> mayChange() {
2230 // User can change himself (but not create)
2231 if (trans.user().equals(cred.id)) {
2235 nsd = ques.validNSOfDomain(trans, cred.id);
2237 // Get the Namespace
2239 if (ques.mayUser(trans, trans.user(), nsd.value,Access.write).isOK()) {
2242 String user[] = Split.split('.',trans.user());
2243 if (user.length>2) {
2244 String company = user[user.length-1] + '.' + user[user.length-2];
2245 if (ques.isGranted(trans, trans.user(), ROOT_NS,"password",company,"reset")) {
2250 return Result.err(Status.ERR_Denied,"%s is not allowed to change %s in %s",trans.user(),cred.id,cred.ns);
2255 private final long DAY_IN_MILLIS = 24*3600*1000L;
2259 path = "/authn/cred",
2262 errorCodes = {403,404,406,409},
2263 text = { "A credential consists of:",
2264 "<ul><li>id - the ID to create within AAF. The domain is in reverse",
2265 "order of Namespace (i.e. Users of Namespace com.att.myapp would be",
2266 "AB1234@myapp.att.com</li>",
2267 "<li>password - Company Policy Compliant Password</li></ul>",
2268 "Note: AAF does support multiple credentials with the same ID.",
2269 "Check with your organization if you have this implemented."
2273 public Result<Void> createUserCred(final AuthzTrans trans, REQUEST from) {
2274 final String cmdDescription = ("Create User Credential");
2275 TimeTaken tt = trans.start(cmdDescription, Env.SUB);
2278 Result<CredDAO.Data> rcred = mapper.cred(trans, from, true);
2279 if (rcred.isOKhasData()) {
2280 byte[] rawCred = rcred.value.cred.array();
2281 rcred = ques.userCredSetup(trans, rcred.value);
2283 final ServiceValidator v = new ServiceValidator();
2285 if (v.cred(trans, trans.org(),rcred,true).err()) { // Note: Creates have stricter Validations
2286 return Result.err(Status.ERR_BadData,v.errs());
2290 // 2016-4 Jonathan, New Behavior - If MechID is not registered with Org, deny creation
2291 Identity mechID = null;
2292 Organization org = trans.org();
2294 mechID = org.getIdentity(trans, rcred.value.id);
2295 } catch (Exception e1) {
2296 trans.error().log(e1,rcred.value.id,"cannot be validated at this time");
2298 if (mechID==null || !mechID.isFound()) {
2299 return Result.err(Status.ERR_Policy,"MechIDs must be registered with %s before provisioning in AAF",org.getName());
2302 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns);
2303 if (nsr.notOKorIsEmpty()) {
2304 return Result.err(Status.ERR_NsNotFound,"Cannot provision %s on non-existent Namespace %s",mechID.id(),rcred.value.ns);
2308 boolean firstID = false;
2311 CassExecutor exec = new CassExecutor(trans, func);
2312 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id);
2313 if (rlcd.isOKhasData()) {
2314 if (!org.canHaveMultipleCreds(rcred.value.id)) {
2315 return Result.err(Status.ERR_ConflictAlreadyExists, "Credential exists");
2318 for (CredDAO.Data curr : rlcd.value) {
2319 // May not use the same password in the list
2320 // Note: ASPR specifies character differences, but we don't actually store the
2321 // password to validate char differences.
2323 rb = ques.userCredCheck(trans, curr, rawCred);
2325 return Result.err(rb);
2326 } else if (rb.value){
2327 return Result.err(Status.ERR_Policy, "Credential content cannot be reused.");
2328 } else if (Chrono.dateOnlyStamp(curr.expires).equals(Chrono.dateOnlyStamp(rcred.value.expires)) && curr.type==rcred.value.type) {
2329 return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists, use 'reset'");
2334 // 2016-04-12 Jonathan If Caller is the Sponsor and is also an Owner of NS, allow without special Perm
2335 String theMechID = rcred.value.id;
2336 Boolean otherMechIDs = false;
2337 // find out if this is the only mechID. other MechIDs mean special handling (not automated)
2338 for (CredDAO.Data cd : ques.credDAO.readNS(trans,nsr.value.get(0).name).value) {
2339 if (!cd.id.equals(theMechID)) {
2340 otherMechIDs = true;
2345 // We can say "ID does not exist" here
2346 if ((reason=org.validate(trans, Policy.CREATE_MECHID, exec, theMechID,trans.user(),otherMechIDs.toString()))!=null) {
2347 return Result.err(Status.ERR_Denied, reason);
2350 } catch (Exception e) {
2351 return Result.err(e);
2355 mc = new MayCreateCred(trans, rcred.value, exec);
2357 final CredDAO.Data cdd = rcred.value;
2358 Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false, // may want to enable in future.
2361 public String get() {
2362 return cmdDescription + " [" +
2365 + cdd.expires + ']';
2372 Result<String> rfc = func.createFuture(trans, fd.value,
2373 rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires,
2374 trans.user(), nsr.value.get(0), FUTURE_OP.C);
2376 return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s] is saved for future processing",
2378 Integer.toString(rcred.value.type),
2379 rcred.value.expires.toString());
2381 return Result.err(rfc);
2383 case Status.ACC_Now:
2386 // && !nsr.value.get(0).isAdmin(trans.getUserPrincipal().getName())) {
2387 Result<List<String>> admins = func.getAdmins(trans, nsr.value.get(0).name, false);
2388 // OK, it's a first ID, and not by NS Admin, so let's set TempPassword length
2389 // Note, we only do this on First time, because of possibility of
2390 // prematurely expiring a production id
2391 if (admins.isOKhasData() && !admins.value.contains(trans.user())) {
2392 rcred.value.expires = org.expiration(null, Expiration.TempPassword).getTime();
2395 } catch (Exception e) {
2396 trans.error().log(e, "While setting expiration to TempPassword");
2399 Result<?>udr = ques.credDAO.create(trans, rcred.value);
2403 return Result.err(udr);
2405 return Result.err(fd);
2409 return Result.err(rcred);
2418 path = "/authn/creds/ns/:ns",
2419 params = {"ns|string|true"},
2421 errorCodes = {403,404,406},
2422 text = { "Return all IDs in Namespace :ns"
2426 public Result<USERS> getCredsByNS(AuthzTrans trans, String ns) {
2427 final Validator v = new ServiceValidator();
2428 if (v.ns(ns).err()) {
2429 return Result.err(Status.ERR_BadData,v.errs());
2432 // check if user is allowed to view NS
2433 Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
2435 return Result.err(rnd);
2437 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
2439 return Result.err(rnd);
2442 TimeTaken tt = trans.start("MAP Creds by NS to Creds", Env.SUB);
2444 USERS users = mapper.newInstance(API.USERS);
2445 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readNS(trans, ns);
2448 if (!rlcd.isEmpty()) {
2449 return mapper.cred(rlcd.value, users);
2451 return Result.ok(users);
2453 return Result.err(rlcd);
2463 path = "/authn/creds/id/:ns",
2464 params = {"id|string|true"},
2466 errorCodes = {403,404,406},
2467 text = { "Return all IDs in for ID"
2468 ,"(because IDs are multiple, due to multiple Expiration Dates)"
2472 public Result<USERS> getCredsByID(AuthzTrans trans, String id) {
2473 final Validator v = new ServiceValidator();
2474 if (v.nullOrBlank("ID",id).err()) {
2475 return Result.err(Status.ERR_BadData,v.errs());
2478 String ns = Question.domain2ns(id);
2479 // check if user is allowed to view NS
2480 Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
2482 return Result.err(rnd);
2484 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
2486 return Result.err(rnd);
2489 TimeTaken tt = trans.start("MAP Creds by ID to Creds", Env.SUB);
2491 USERS users = mapper.newInstance(API.USERS);
2492 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, id);
2495 if (!rlcd.isEmpty()) {
2496 return mapper.cred(rlcd.value, users);
2498 return Result.ok(users);
2500 return Result.err(rlcd);
2510 path = "/authn/certs/id/:id",
2511 params = {"id|string|true"},
2513 errorCodes = {403,404,406},
2514 text = { "Return Cert Info for ID"
2518 public Result<CERTS> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id) {
2519 TimeTaken tt = trans.start("Get Cert Info by ID", Env.SUB);
2521 CERTS certs = mapper.newInstance(API.CERTS);
2522 Result<List<CertDAO.Data>> rlcd = ques.certDAO.readID(trans, id);
2525 if (!rlcd.isEmpty()) {
2526 return mapper.cert(rlcd.value, certs);
2528 return Result.ok(certs);
2530 return Result.err(rlcd);
2540 path = "/authn/cred",
2543 errorCodes = {300,403,404,406},
2544 text = { "Reset a Credential Password. If multiple credentials exist for this",
2545 "ID, you will need to specify which entry you are resetting in the",
2546 "CredRequest object"
2550 public Result<Void> changeUserCred(final AuthzTrans trans, REQUEST from) {
2551 final String cmdDescription = "Update User Credential";
2552 TimeTaken tt = trans.start(cmdDescription, Env.SUB);
2554 Result<CredDAO.Data> rcred = mapper.cred(trans, from, true);
2555 if (rcred.isOKhasData()) {
2556 rcred = ques.userCredSetup(trans, rcred.value);
2558 final ServiceValidator v = new ServiceValidator();
2560 if (v.cred(trans, trans.org(),rcred,false).err()) {// Note: Creates have stricter Validations
2561 return Result.err(Status.ERR_BadData,v.errs());
2563 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id);
2564 if (rlcd.notOKorIsEmpty()) {
2565 return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
2568 MayChange mc = new MayChangeCred(trans, rcred.value);
2569 Result<?> rmc = mc.mayChange();
2571 return Result.err(rmc);
2574 Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value);
2576 return Result.err(ri);
2578 int entry = ri.value;
2581 final CredDAO.Data cred = rcred.value;
2583 Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false,
2586 public String get() {
2587 return cmdDescription + " [" +
2590 + cred.expires + ']';
2595 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns);
2596 if (nsr.notOKorIsEmpty()) {
2597 return Result.err(nsr);
2602 Result<String> rfc = func.createFuture(trans, fd.value,
2603 rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires,
2604 trans.user(), nsr.value.get(0), FUTURE_OP.U);
2606 return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s]",
2608 Integer.toString(rcred.value.type),
2609 rcred.value.expires.toString());
2611 return Result.err(rfc);
2613 case Status.ACC_Now:
2614 Result<?>udr = null;
2615 // If we are Resetting Password on behalf of someone else (am not the Admin)
2616 // use TempPassword Expiration time.
2618 if (ques.isAdmin(trans, trans.user(), nsr.value.get(0).name)) {
2619 exp = Expiration.Password;
2621 exp = Expiration.TempPassword;
2624 Organization org = trans.org();
2625 CredDAO.Data current = rlcd.value.get(entry);
2626 // If user resets password in same day, we will have a primary key conflict, so subtract 1 day
2627 if (current.expires.equals(rcred.value.expires)
2628 && rlcd.value.get(entry).type==rcred.value.type) {
2629 GregorianCalendar gc = org.expiration(null, exp,rcred.value.id);
2630 gc = Chrono.firstMomentOfDay(gc);
2631 gc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay());
2632 rcred.value.expires = new Date(gc.getTimeInMillis() - DAY_IN_MILLIS);
2634 rcred.value.expires = org.expiration(null,exp).getTime();
2637 udr = ques.credDAO.create(trans, rcred.value);
2639 udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false);
2645 return Result.err(udr);
2647 return Result.err(fd);
2650 return Result.err(rcred);
2658 * Codify the way to get Either Choice Needed or actual Integer from Credit Request
2660 private Result<Integer> selectEntryIfMultiple(final CredRequest cr, List<CredDAO.Data> lcd) {
2662 if (lcd.size() > 1) {
2663 String inputOption = cr.getEntry();
2664 if (inputOption == null) {
2665 String message = selectCredFromList(lcd, false);
2666 Object[] variables = buildVariables(lcd);
2667 return Result.err(Status.ERR_ChoiceNeeded, message, variables);
2669 entry = Integer.parseInt(inputOption) - 1;
2671 if (entry < 0 || entry >= lcd.size()) {
2672 return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
2675 return Result.ok(entry);
2680 path = "/authn/cred/:days",
2681 params = {"days|string|true"},
2683 errorCodes = {300,403,404,406},
2684 text = { "Extend a Credential Expiration Date. The intention of this API is",
2685 "to avoid an outage in PROD due to a Credential expiring before it",
2686 "can be configured correctly. Measures are being put in place ",
2687 "so that this is not abused."
2691 public Result<Void> extendUserCred(final AuthzTrans trans, REQUEST from, String days) {
2692 TimeTaken tt = trans.start("Extend User Credential", Env.SUB);
2694 Result<CredDAO.Data> cred = mapper.cred(trans, from, false);
2695 Organization org = trans.org();
2696 final ServiceValidator v = new ServiceValidator();
2697 if (v.notOK(cred).err() ||
2698 v.nullOrBlank(cred.value.id, "Invalid ID").err() ||
2699 v.user(org,cred.value.id).err()) {
2700 return Result.err(Status.ERR_BadData,v.errs());
2705 if ((reason=org.validate(trans, Policy.MAY_EXTEND_CRED_EXPIRES, new CassExecutor(trans,func)))!=null) {
2706 return Result.err(Status.ERR_Policy,reason);
2708 } catch (Exception e) {
2710 trans.error().log(e, msg="Could not contact Organization for User Validation");
2711 return Result.err(Status.ERR_Denied, msg);
2714 // Get the list of Cred Entries
2715 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id);
2716 if (rlcd.notOKorIsEmpty()) {
2717 return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
2720 //Need to do the "Pick Entry" mechanism
2721 Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value);
2723 return Result.err(ri);
2726 CredDAO.Data found = rlcd.value.get(ri.value);
2727 CredDAO.Data cd = cred.value;
2728 // Copy over the cred
2730 cd.cred = found.cred;
2731 cd.other = found.other;
2732 cd.type = found.type;
2734 cd.expires = org.expiration(null, Expiration.ExtendPassword,days).getTime();
2737 cred = ques.credDAO.create(trans, cd);
2741 return Result.err(cred);
2747 private String[] buildVariables(List<CredDAO.Data> value) {
2748 // ensure credentials are sorted so we can fully automate Cred regression test
2749 Collections.sort(value, (cred1, cred2) -> cred1.expires.compareTo(cred2.expires));
2750 String [] vars = new String[value.size()+1];
2752 for (int i = 0; i < value.size(); i++) {
2753 vars[i+1] = value.get(i).id + " " + value.get(i).type
2754 + " |" + value.get(i).expires;
2759 private String selectCredFromList(List<CredDAO.Data> value, boolean isDelete) {
2760 StringBuilder errMessage = new StringBuilder();
2761 String userPrompt = isDelete?"Select which cred to delete (set force=true to delete all):":"Select which cred to update:";
2762 int numSpaces = value.get(0).id.length() - "Id".length();
2764 errMessage.append(userPrompt + '\n');
2765 errMessage.append(" Id");
2766 for (int i = 0; i < numSpaces; i++) {
2767 errMessage.append(' ');
2769 errMessage.append(" Type Expires" + '\n');
2770 for (int i=0;i<value.size();++i) {
2771 errMessage.append(" %s\n");
2773 errMessage.append("Run same command again with chosen entry as last parameter");
2775 return errMessage.toString();
2781 path = "/authn/cred",
2784 errorCodes = {300,403,404,406},
2785 text = { "Delete a Credential. If multiple credentials exist for this",
2786 "ID, you will need to specify which entry you are deleting in the",
2787 "CredRequest object."
2791 public Result<Void> deleteUserCred(AuthzTrans trans, REQUEST from) {
2792 final Result<CredDAO.Data> cred = mapper.cred(trans, from, false);
2793 final Validator v = new ServiceValidator();
2794 if (v.nullOrBlank("cred", cred.value.id).err()) {
2795 return Result.err(Status.ERR_BadData,v.errs());
2798 Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id);
2799 if (rlcd.notOKorIsEmpty()) {
2800 // Empty Creds should have no user_roles.
2801 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id);
2803 for (UserRoleDAO.Data data : rlurd.value) {
2804 ques.userRoleDAO.delete(trans, data, false);
2807 return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
2809 boolean isLastCred = rlcd.value.size()==1;
2811 MayChange mc = new MayChangeCred(trans,cred.value);
2812 Result<?> rmc = mc.mayChange();
2814 return Result.err(rmc);
2818 if (!trans.requested(force)) {
2819 if (rlcd.value.size() > 1) {
2820 CredRequest cr = (CredRequest)from;
2821 String inputOption = cr.getEntry();
2822 if (inputOption == null) {
2823 String message = selectCredFromList(rlcd.value, true);
2824 Object[] variables = buildVariables(rlcd.value);
2825 return Result.err(Status.ERR_ChoiceNeeded, message, variables);
2828 if (inputOption.length()>5) { // should be a date
2829 Date d = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(inputOption).toGregorianCalendar().getTime();
2831 for (CredDAO.Data cd : rlcd.value) {
2832 if (cd.type.equals(cr.getType()) && cd.expires.equals(d)) {
2838 entry = Integer.parseInt(inputOption) - 1;
2840 } catch (NullPointerException e) {
2841 return Result.err(Status.ERR_BadData, "Invalid Date Format for Entry");
2842 } catch (NumberFormatException e) {
2843 return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
2846 isLastCred = (entry==-1)?true:false;
2850 if (entry < -1 || entry >= rlcd.value.size()) {
2851 return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
2855 Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from,cred.value,false,
2856 () -> "Delete Credential [" +
2861 Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, cred.value.ns);
2862 if (nsr.notOKorIsEmpty()) {
2863 return Result.err(nsr);
2868 Result<String> rfc = func.createFuture(trans, fd.value, cred.value.id,
2869 trans.user(), nsr.value.get(0), FUTURE_OP.D);
2872 return Result.err(Status.ACC_Future, "Credential Delete [%s] is saved for future processing",cred.value.id);
2874 return Result.err(rfc);
2876 case Status.ACC_Now:
2877 Result<?>udr = null;
2878 if (!trans.requested(force)) {
2879 if (entry<0 || entry >= rlcd.value.size()) {
2880 return Result.err(Status.ERR_BadData,"Invalid Choice [" + entry + "] chosen for Delete [%s] is saved for future processing",cred.value.id);
2882 udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false);
2884 for (CredDAO.Data curr : rlcd.value) {
2885 udr = ques.credDAO.delete(trans, curr, false);
2887 return Result.err(udr);
2892 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id);
2894 for (UserRoleDAO.Data data : rlurd.value) {
2895 ques.userRoleDAO.delete(trans, data, false);
2900 return Result.err(Result.ERR_NotFound,"No User Data found");
2905 return Result.err(udr);
2907 return Result.err(fd);
2914 public Result<Date> doesCredentialMatch(AuthzTrans trans, REQUEST credReq) {
2915 TimeTaken tt = trans.start("Does Credential Match", Env.SUB);
2917 // Note: Mapper assigns RAW type
2918 Result<CredDAO.Data> data = mapper.cred(trans, credReq,false);
2919 if (data.notOKorIsEmpty()) {
2920 return Result.err(data);
2922 CredDAO.Data cred = data.value; // of the Mapped Cred
2923 if (cred.cred==null) {
2924 return Result.err(Result.ERR_BadData,"No Password");
2926 return ques.doesUserCredMatch(trans, cred.id, cred.cred.array());
2929 } catch (DAOException e) {
2930 trans.error().log(e,"Error looking up cred");
2931 return Result.err(Status.ERR_Denied,"Credential does not match");
2939 path = "/authn/basicAuth",
2942 errorCodes = { 403 },
2943 text = { "!!!! DEPRECATED without X509 Authentication STOP USING THIS API BY DECEMBER 2017, or use Certificates !!!!\n"
2944 + "Use /authn/validate instead\n"
2945 + "Note: Validate a Password using BasicAuth Base64 encoded Header. This HTTP/S call is intended as a fast"
2946 + " User/Password lookup for Security Frameworks, and responds 200 if it passes BasicAuth "
2947 + "security, and 403 if it does not." }
2949 private void basicAuth() {
2950 // This is a place holder for Documentation. The real BasicAuth API does not call Service.
2955 path = "/authn/validate",
2958 errorCodes = { 403 },
2959 text = { "Validate a Credential given a Credential Structure. This is a more comprehensive validation, can "
2960 + "do more than BasicAuth as Credential types exp" }
2963 public Result<Date> validateBasicAuth(AuthzTrans trans, String basicAuth) {
2964 //TODO how to make sure people don't use this in browsers? Do we care?
2965 TimeTaken tt = trans.start("Validate Basic Auth", Env.SUB);
2967 BasicPrincipal bp = new BasicPrincipal(basicAuth,trans.org().getRealm());
2968 Result<Date> rq = ques.doesUserCredMatch(trans, bp.getName(), bp.getCred());
2969 // Note: Only want to log problem, don't want to send back to end user
2973 trans.audit().log(rq.errorString());
2975 } catch (Exception e) {
2976 trans.warn().log(e);
2980 return Result.err(Status.ERR_Denied,"Bad Basic Auth");
2983 /***********************************
2985 ***********************************/
2988 path = "/authz/userRole",
2991 errorCodes = {403,404,406,409},
2992 text = { "Create a UserRole relationship (add User to Role)",
2993 "A UserRole is an object Representation of membership of a Role for limited time.",
2994 "If a shorter amount of time for Role ownership is required, use the 'End' field.",
2995 "** Note: Owners of Namespaces will be required to revalidate users in these roles ",
2996 "before Expirations expire. Namespace owners will be notified by email."
3000 public Result<Void> createUserRole(final AuthzTrans trans, REQUEST from) {
3001 TimeTaken tt = trans.start("Create UserRole", Env.SUB);
3003 Result<UserRoleDAO.Data> urr = mapper.userRole(trans, from);
3004 if (urr.notOKorIsEmpty()) {
3005 return Result.err(urr);
3007 final UserRoleDAO.Data userRole = urr.value;
3009 final ServiceValidator v = new ServiceValidator();
3010 if (v.user_role(userRole).err() ||
3011 v.user(trans.org(), userRole.user).err()) {
3012 return Result.err(Status.ERR_BadData,v.errs());
3017 // Check if user can change first
3018 Result<FutureDAO.Data> fd = mapper.future(trans,UserRoleDAO.TABLE,from,urr.value,true, // may request Approvals
3019 () -> "Add User [" + userRole.user + "] to Role [" +
3023 private Result<NsDAO.Data> nsd;
3025 public Result<?> mayChange() {
3027 RoleDAO.Data r = RoleDAO.Data.decode(userRole);
3028 nsd = ques.mayUser(trans, trans.user(), r, Access.write);
3033 Result<NsDAO.Data> nsr = ques.deriveNs(trans, userRole.role);
3034 if (nsr.notOKorIsEmpty()) {
3035 return Result.err(nsr);
3040 Result<String> rfc = func.createFuture(trans, fd.value, userRole.user+'|'+userRole.ns + '.' + userRole.rname,
3041 userRole.user, nsr.value, FUTURE_OP.C);
3043 return Result.err(Status.ACC_Future, "UserRole [%s - %s.%s] is saved for future processing",
3048 return Result.err(rfc);
3050 case Status.ACC_Now:
3051 return func.addUserRole(trans, userRole);
3053 return Result.err(fd);
3061 * getUserRolesByRole
3065 path = "/authz/userRoles/role/:role",
3066 params = {"role|string|true"},
3068 errorCodes = {404,406},
3069 text = { "List all Users that are attached to Role specified in :role",
3073 public Result<USERROLES> getUserRolesByRole(AuthzTrans trans, String role) {
3074 final Validator v = new ServiceValidator();
3075 if (v.nullOrBlank("Role",role).err()) {
3076 return Result.err(Status.ERR_BadData,v.errs());
3079 Result<RoleDAO.Data> rrdd;
3080 rrdd = RoleDAO.Data.decode(trans,ques,role);
3082 return Result.err(rrdd);
3084 // May Requester see result?
3085 Result<NsDAO.Data> ns = ques.mayUser(trans,trans.user(), rrdd.value,Access.read);
3087 return Result.err(ns);
3090 // boolean filter = true;
3091 // if (ns.value.isAdmin(trans.user()) || ns.value.isResponsible(trans.user()))
3094 // Get list of roles per user, then add to Roles as we go
3095 HashSet<UserRoleDAO.Data> userSet = new HashSet<>();
3096 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role);
3098 for (UserRoleDAO.Data data : rlurd.value) {
3103 @SuppressWarnings("unchecked")
3104 USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES);
3105 // Checked for permission
3106 mapper.userRoles(trans, userSet, users);
3107 return Result.ok(users);
3110 * getUserRolesByRole
3114 path = "/authz/userRoles/user/:user",
3115 params = {"role|string|true"},
3117 errorCodes = {404,406},
3118 text = { "List all UserRoles for :user",
3122 public Result<USERROLES> getUserRolesByUser(AuthzTrans trans, String user) {
3123 final Validator v = new ServiceValidator();
3124 if (v.nullOrBlank("User",user).err()) {
3125 return Result.err(Status.ERR_BadData,v.errs());
3128 // Get list of roles per user, then add to Roles as we go
3129 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user);
3130 if (rlurd.notOK()) {
3131 return Result.err(rlurd);
3136 * 2) is User's Supervisor
3137 * 3) Has special global access =read permission
3139 * If none of the 3, then filter results to NSs in which Calling User has Ns.access * read
3142 String callingUser = trans.getUserPrincipal().getName();
3143 NsDAO.Data ndd = new NsDAO.Data();
3145 if (user.equals(callingUser)) {
3148 Organization org = trans.org();
3150 Identity orgID = org.getIdentity(trans, user);
3151 Identity manager = orgID==null?null:orgID.responsibleTo();
3152 if (orgID!=null && (manager!=null && callingUser.equals(manager.fullID()))) {
3154 } else if (ques.isGranted(trans, callingUser, ROOT_NS, Question.ACCESS, "*", Access.read.name())) {
3159 } catch (OrganizationException e) {
3165 List<UserRoleDAO.Data> content;
3167 content = new ArrayList<>(rlurd.value.size()); // avoid multi-memory redos
3169 for (UserRoleDAO.Data data : rlurd.value) {
3171 Result<Data> mur = ques.mayUser(trans, callingUser, ndd, Access.read);
3178 content = rlurd.value;
3182 @SuppressWarnings("unchecked")
3183 USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES);
3184 // Checked for permission
3185 mapper.userRoles(trans, content, users);
3186 return Result.ok(users);
3192 path = "/authz/userRole/user",
3195 errorCodes = {403,404,406},
3196 text = { "Set a User's roles to the roles specified in the UserRoleRequest object.",
3197 "WARNING: Roles supplied will be the ONLY roles attached to this user",
3198 "If no roles are supplied, user's roles are reset."
3202 public Result<Void> resetRolesForUser(AuthzTrans trans, REQUEST rreq) {
3203 Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq);
3204 final ServiceValidator v = new ServiceValidator();
3205 if (rurdd.notOKorIsEmpty()) {
3206 return Result.err(rurdd);
3208 if (v.user(trans.org(), rurdd.value.user).err()) {
3209 return Result.err(Status.ERR_BadData,v.errs());
3212 Set<String> currRoles = new HashSet<>();
3213 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, rurdd.value.user);
3215 for (UserRoleDAO.Data data : rlurd.value) {
3216 currRoles.add(data.role);
3220 Result<Void> rv = null;
3222 if (rurdd.value.role==null) {
3223 roles = new String[0];
3225 roles = rurdd.value.role.split(",");
3228 for (String role : roles) {
3229 if (v.role(role).err()) {
3230 return Result.err(Status.ERR_BadData,v.errs());
3232 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
3234 return Result.err(rrdd);
3237 rurdd.value.role(rrdd.value);
3239 Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), rrdd.value,Access.write);
3241 return Result.err(nsd);
3243 Result<NsDAO.Data> nsr = ques.deriveNs(trans, role);
3244 if (nsr.notOKorIsEmpty()) {
3245 return Result.err(nsr);
3248 if (currRoles.contains(role)) {
3249 currRoles.remove(role);
3251 rv = func.addUserRole(trans, rurdd.value);
3258 for (String role : currRoles) {
3259 rurdd.value.role(trans,ques,role);
3260 rv = ques.userRoleDAO.delete(trans, rurdd.value, false);
3262 trans.info().log(rurdd.value.user,"/",rurdd.value.role, "expected to be deleted, but does not exist");
3263 // return rv; // if it doesn't exist, don't error out
3274 path = "/authz/userRole/role",
3277 errorCodes = {403,404,406},
3278 text = { "Set a Role's users to the users specified in the UserRoleRequest object.",
3279 "WARNING: Users supplied will be the ONLY users attached to this role",
3280 "If no users are supplied, role's users are reset."
3284 public Result<Void> resetUsersForRole(AuthzTrans trans, REQUEST rreq) {
3285 Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq);
3286 if (rurdd.notOKorIsEmpty()) {
3287 return Result.err(rurdd);
3289 final ServiceValidator v = new ServiceValidator();
3290 if (v.user_role(rurdd.value).err()) {
3291 return Result.err(Status.ERR_BadData,v.errs());
3294 RoleDAO.Data rd = RoleDAO.Data.decode(rurdd.value);
3296 Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), rd, Access.write);
3298 return Result.err(nsd);
3301 Result<NsDAO.Data> nsr = ques.deriveNs(trans, rurdd.value.role);
3302 if (nsr.notOKorIsEmpty()) {
3303 return Result.err(nsr);
3306 Set<String> currUsers = new HashSet<>();
3307 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, rurdd.value.role);
3309 for (UserRoleDAO.Data data : rlurd.value) {
3310 currUsers.add(data.user);
3314 // found when connected remotely to DEVL, can't replicate locally
3315 // inconsistent errors with cmd: role user setTo [nothing]
3316 // deleteUserRole --> read --> get --> cacheIdx(?)
3317 // sometimes returns idx for last added user instead of user passed in
3321 Result<Void> rv = null;
3322 String[] users = {};
3323 if (rurdd.value.user != null) {
3324 users = rurdd.value.user.split(",");
3327 for (String user : users) {
3328 if (v.user(trans.org(), user).err()) {
3329 return Result.err(Status.ERR_BadData,v.errs());
3331 rurdd.value.user = user;
3333 if (currUsers.contains(user)) {
3334 currUsers.remove(user);
3336 rv = func.addUserRole(trans, rurdd.value);
3343 for (String user : currUsers) {
3344 rurdd.value.user = user;
3345 rv = ques.userRoleDAO.delete(trans, rurdd.value, false);
3347 trans.info().log(rurdd.value, "expected to be deleted, but not exists");
3357 path = "/authz/userRole/extend/:user/:role",
3358 params = { "user|string|true",
3362 errorCodes = {403,404,406},
3363 text = { "Extend the Expiration of this User Role by the amount set by Organization",
3364 "Requestor must be allowed to modify the role"
3368 public Result<Void> extendUserRole(AuthzTrans trans, String user, String role) {
3369 Organization org = trans.org();
3370 final ServiceValidator v = new ServiceValidator();
3371 if (v.user(org, user)
3374 return Result.err(Status.ERR_BadData,v.errs());
3377 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
3379 return Result.err(rrdd);
3382 Result<NsDAO.Data> rcr = ques.mayUser(trans, trans.user(), rrdd.value, Access.write);
3383 boolean mayNotChange;
3384 if ((mayNotChange = rcr.notOK()) && !trans.requested(future)) {
3385 return Result.err(rcr);
3388 Result<List<UserRoleDAO.Data>> rr = ques.userRoleDAO.read(trans, user,role);
3390 return Result.err(rr);
3392 for (UserRoleDAO.Data userRole : rr.value) {
3393 if (mayNotChange) { // Function exited earlier if !trans.futureRequested
3394 FutureDAO.Data fto = new FutureDAO.Data();
3395 fto.target=UserRoleDAO.TABLE;
3396 fto.memo = "Extend User ["+userRole.user+"] in Role ["+userRole.role+"]";
3397 GregorianCalendar now = new GregorianCalendar();
3398 fto.start = now.getTime();
3399 fto.expires = org.expiration(now, Expiration.Future).getTime();
3401 fto.construct = userRole.bytify();
3402 } catch (IOException e) {
3403 trans.error().log(e, "Error while bytifying UserRole for Future");
3404 return Result.err(e);
3407 Result<String> rfc = func.createFuture(trans, fto,
3408 userRole.user+'|'+userRole.role, userRole.user, rcr.value, FUTURE_OP.U);
3410 return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing",
3414 return Result.err(rfc);
3417 return func.extendUserRole(trans, userRole, false);
3420 return Result.err(Result.ERR_NotFound,"This user and role doesn't exist");
3425 path = "/authz/userRole/:user/:role",
3426 params = { "user|string|true",
3430 errorCodes = {403,404,406},
3431 text = { "Remove Role :role from User :user."
3435 public Result<Void> deleteUserRole(AuthzTrans trans, String usr, String role) {
3436 Validator val = new ServiceValidator();
3437 if (val.nullOrBlank("User", usr)
3438 .nullOrBlank("Role", role).err()) {
3439 return Result.err(Status.ERR_BadData, val.errs());
3442 boolean mayNotChange;
3443 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
3445 return Result.err(rrdd);
3448 RoleDAO.Data rdd = rrdd.value;
3449 Result<NsDAO.Data> rns = ques.mayUser(trans, trans.user(), rdd, Access.write);
3451 // Make sure we don't delete the last owner of valid NS
3452 if (rns.isOKhasData() && Question.OWNER.equals(rdd.name) && ques.countOwner(trans,rdd.ns)<=1) {
3453 return Result.err(Status.ERR_Denied,"You may not delete the last Owner of " + rdd.ns );
3456 if (mayNotChange=rns.notOK()) {
3457 if (!trans.requested(future)) {
3458 return Result.err(rns);
3462 Result<List<UserRoleDAO.Data>> rulr;
3463 if ((rulr=ques.userRoleDAO.read(trans, usr, role)).notOKorIsEmpty()) {
3464 return Result.err(Status.ERR_UserRoleNotFound, "User [ "+usr+" ] is not "
3465 + "Assigned to the Role [ " + role + " ]");
3468 UserRoleDAO.Data userRole = rulr.value.get(0);
3469 if (mayNotChange) { // Function exited earlier if !trans.futureRequested
3470 FutureDAO.Data fto = new FutureDAO.Data();
3471 fto.target=UserRoleDAO.TABLE;
3472 fto.memo = "Remove User ["+userRole.user+"] from Role ["+userRole.role+"]";
3473 GregorianCalendar now = new GregorianCalendar();
3474 fto.start = now.getTime();
3475 fto.expires = trans.org().expiration(now, Expiration.Future).getTime();
3477 Result<String> rfc = func.createFuture(trans, fto,
3478 userRole.user+'|'+userRole.role, userRole.user, rns.value, FUTURE_OP.D);
3480 return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing",
3484 return Result.err(rfc);
3487 return ques.userRoleDAO.delete(trans, rulr.value.get(0), false);
3493 path = "/authz/userRole/:user/:role",
3494 params = {"user|string|true",
3495 "role|string|true"},
3497 errorCodes = {403,404,406},
3498 text = { "Returns the User (with Expiration date from listed User/Role) if it exists"
3502 public Result<USERS> getUserInRole(AuthzTrans trans, String user, String role) {
3503 final Validator v = new ServiceValidator();
3504 if (v.role(role).nullOrBlank("User", user).err()) {
3505 return Result.err(Status.ERR_BadData,v.errs());
3508 // Result<NsDAO.Data> ns = ques.deriveNs(trans, role);
3509 // if (ns.notOK()) return Result.err(ns);
3511 // Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write);
3512 // May calling user see by virtue of the Role
3513 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
3515 return Result.err(rrdd);
3517 Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read);
3519 return Result.err(rnd);
3522 HashSet<UserRoleDAO.Data> userSet = new HashSet<>();
3523 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readUserInRole(trans, user, role);
3525 for (UserRoleDAO.Data data : rlurd.value) {
3530 @SuppressWarnings("unchecked")
3531 USERS users = (USERS) mapper.newInstance(API.USERS);
3532 mapper.users(trans, userSet, users);
3533 return Result.ok(users);
3538 path = "/authz/users/role/:role",
3539 params = {"user|string|true",
3540 "role|string|true"},
3542 errorCodes = {403,404,406},
3543 text = { "Returns the User (with Expiration date from listed User/Role) if it exists"
3547 public Result<USERS> getUsersByRole(AuthzTrans trans, String role) {
3548 final Validator v = new ServiceValidator();
3549 if (v.nullOrBlank("Role",role).err()) {
3550 return Result.err(Status.ERR_BadData,v.errs());
3553 // Result<NsDAO.Data> ns = ques.deriveNs(trans, role);
3554 // if (ns.notOK()) return Result.err(ns);
3556 // Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write);
3557 // May calling user see by virtue of the Role
3558 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
3560 return Result.err(rrdd);
3563 boolean contactOnly = false;
3564 // Allow the request of any valid user to find the contact of the NS (Owner)
3565 Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read);
3567 if (Question.OWNER.equals(rrdd.value.name)) {
3570 return Result.err(rnd);
3574 HashSet<UserRoleDAO.Data> userSet = new HashSet<>();
3575 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role);
3577 for (UserRoleDAO.Data data : rlurd.value) {
3578 if (contactOnly) { //scrub data
3579 // Can't change actual object, or will mess up the cache.
3580 UserRoleDAO.Data scrub = new UserRoleDAO.Data();
3582 scrub.rname = data.rname;
3583 scrub.role = data.role;
3584 scrub.user = data.user;
3592 @SuppressWarnings("unchecked")
3593 USERS users = (USERS) mapper.newInstance(API.USERS);
3594 mapper.users(trans, userSet, users);
3595 return Result.ok(users);
3599 * getUsersByPermission
3603 path = "/authz/users/perm/:type/:instance/:action",
3604 params = { "type|string|true",
3605 "instance|string|true",
3606 "action|string|true"
3609 errorCodes = {404,406},
3610 text = { "List all Users that have Permission specified by :type :instance :action",
3614 public Result<USERS> getUsersByPermission(AuthzTrans trans, String type, String instance, String action) {
3615 final Validator v = new ServiceValidator();
3616 if (v.nullOrBlank("Type",type)
3617 .nullOrBlank("Instance",instance)
3618 .nullOrBlank("Action",action)
3620 return Result.err(Status.ERR_BadData,v.errs());
3623 Result<NsSplit> nss = ques.deriveNsSplit(trans, type);
3625 return Result.err(nss);
3628 Result<List<NsDAO.Data>> nsd = ques.nsDAO.read(trans, nss.value.ns);
3630 return Result.err(nsd);
3633 boolean allInstance = ASTERIX.equals(instance);
3634 boolean allAction = ASTERIX.equals(action);
3635 // Get list of roles per Permission,
3636 // Then loop through Roles to get Users
3637 // Note: Use Sets to avoid processing or responding with Duplicates
3638 Set<String> roleUsed = new HashSet<>();
3639 Set<UserRoleDAO.Data> userSet = new HashSet<>();
3641 if (!nss.isEmpty()) {
3642 Result<List<PermDAO.Data>> rlp = ques.permDAO.readByType(trans, nss.value.ns, nss.value.name);
3643 if (rlp.isOKhasData()) {
3644 for (PermDAO.Data pd : rlp.value) {
3645 if ((allInstance || pd.instance.equals(instance)) &&
3646 (allAction || pd.action.equals(action))) {
3647 if (ques.mayUser(trans, trans.user(),pd,Access.read).isOK()) {
3648 for (String role : pd.roles) {
3649 if (!roleUsed.contains(role)) { // avoid evaluating Role many times
3651 Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role.replace('|', '.'));
3652 if (rlurd.isOKhasData()) {
3653 for (UserRoleDAO.Data urd : rlurd.value) {
3664 @SuppressWarnings("unchecked")
3665 USERS users = (USERS) mapper.newInstance(API.USERS);
3666 mapper.users(trans, userSet, users);
3667 return Result.ok(users);
3670 /***********************************
3672 ***********************************/
3674 public Result<HISTORY> getHistoryByUser(final AuthzTrans trans, String user, final int[] yyyymm, final int sort) {
3675 final Validator v = new ServiceValidator();
3676 if (v.nullOrBlank("User",user).err()) {
3677 return Result.err(Status.ERR_BadData,v.errs());
3680 Result<NsDAO.Data> rnd;
3681 // Users may look at their own data
3682 if (trans.user().equals(user)) {
3683 // Users may look at their own data
3685 int at = user.indexOf('@');
3686 if (at>=0 && trans.org().getRealm().equals(user.substring(at+1))) {
3687 NsDAO.Data nsd = new NsDAO.Data();
3688 nsd.name = Question.domain2ns(user);
3689 rnd = ques.mayUser(trans, trans.user(), nsd, Access.read);
3691 return Result.err(rnd);
3694 rnd = ques.validNSOfDomain(trans, user);
3696 return Result.err(rnd);
3699 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
3701 return Result.err(rnd);
3705 Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readByUser(trans, user, yyyymm);
3707 return Result.err(resp);
3709 return mapper.history(trans, resp.value,sort);
3713 public Result<HISTORY> getHistoryByRole(AuthzTrans trans, String role, int[] yyyymm, final int sort) {
3714 final Validator v = new ServiceValidator();
3715 if (v.nullOrBlank("Role",role).err()) {
3716 return Result.err(Status.ERR_BadData,v.errs());
3719 Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
3721 return Result.err(rrdd);
3724 Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value, Access.read);
3726 return Result.err(rnd);
3728 Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, role, "role", yyyymm);
3730 return Result.err(resp);
3732 return mapper.history(trans, resp.value,sort);
3736 public Result<HISTORY> getHistoryByPerm(AuthzTrans trans, String type, int[] yyyymm, final int sort) {
3737 final Validator v = new ServiceValidator();
3738 if (v.nullOrBlank("Type",type)
3740 return Result.err(Status.ERR_BadData,v.errs());
3743 // May user see Namespace of Permission (since it's only one piece... we can't check for "is permission part of")
3744 Result<NsDAO.Data> rnd = ques.deriveNs(trans,type);
3746 return Result.err(rnd);
3749 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
3751 return Result.err(rnd);
3753 Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, type, "perm", yyyymm);
3755 return Result.err(resp);
3757 return mapper.history(trans, resp.value,sort);
3761 public Result<HISTORY> getHistoryByNS(AuthzTrans trans, String ns, int[] yyyymm, final int sort) {
3762 final Validator v = new ServiceValidator();
3763 if (v.nullOrBlank("NS",ns)
3765 return Result.err(Status.ERR_BadData,v.errs());
3768 Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
3770 return Result.err(rnd);
3772 rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
3774 return Result.err(rnd);
3777 Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, ns, "ns", yyyymm);
3779 return Result.err(resp);
3781 return mapper.history(trans, resp.value,sort);
3784 /***********************************
3786 ***********************************/
3788 public Result<Void> createDelegate(final AuthzTrans trans, REQUEST base) {
3789 return createOrUpdateDelegate(trans, base, Question.Access.create);
3793 public Result<Void> updateDelegate(AuthzTrans trans, REQUEST base) {
3794 return createOrUpdateDelegate(trans, base, Question.Access.write);
3798 private Result<Void> createOrUpdateDelegate(final AuthzTrans trans, REQUEST base, final Access access) {
3799 final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base);
3800 final ServiceValidator v = new ServiceValidator();
3801 if (v.delegate(trans.org(),rd).err()) {
3802 return Result.err(Status.ERR_BadData,v.errs());
3805 final DelegateDAO.Data dd = rd.value;
3807 Result<List<DelegateDAO.Data>> ddr = ques.delegateDAO.read(trans, dd);
3808 if (access==Access.create && ddr.isOKhasData()) {
3809 return Result.err(Status.ERR_ConflictAlreadyExists, "[%s] already delegates to [%s]", dd.user, ddr.value.get(0).delegate);
3810 } else if (access!=Access.create && ddr.notOKorIsEmpty()) {
3811 return Result.err(Status.ERR_NotFound, "[%s] does not have a Delegate Record to [%s].",dd.user,access.name());
3813 Result<Void> rv = ques.mayUser(trans, dd, access);
3818 Result<FutureDAO.Data> fd = mapper.future(trans,DelegateDAO.TABLE,base, dd, false,
3820 StringBuilder sb = new StringBuilder();
3821 sb.append(access.name());
3822 sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
3823 sb.append("Delegate ");
3824 sb.append(access==Access.create?"[":"to [");
3825 sb.append(rd.value.delegate);
3826 sb.append("] for [");
3827 sb.append(rd.value.user);
3829 return sb.toString();
3832 return Result.ok(); // Validate in code above
3837 Result<String> rfc = func.createFuture(trans, fd.value,
3838 dd.user, trans.user(),null, access==Access.create?FUTURE_OP.C:FUTURE_OP.U);
3840 return Result.err(Status.ACC_Future, "Delegate for [%s]",
3843 return Result.err(rfc);
3845 case Status.ACC_Now:
3846 if (access==Access.create) {
3847 Result<DelegateDAO.Data> rdr = ques.delegateDAO.create(trans, dd);
3851 return Result.err(rdr);
3854 return ques.delegateDAO.update(trans, dd);
3857 return Result.err(fd);
3862 public Result<Void> deleteDelegate(AuthzTrans trans, REQUEST base) {
3863 final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base);
3864 final Validator v = new ServiceValidator();
3865 if (v.notOK(rd).nullOrBlank("User", rd.value.user).err()) {
3866 return Result.err(Status.ERR_BadData,v.errs());
3869 Result<List<DelegateDAO.Data>> ddl;
3870 if ((ddl=ques.delegateDAO.read(trans, rd.value)).notOKorIsEmpty()) {
3871 return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate");
3873 final DelegateDAO.Data dd = ddl.value.get(0);
3874 Result<Void> rv = ques.mayUser(trans, dd, Access.write);
3879 return ques.delegateDAO.delete(trans, dd, false);
3883 public Result<Void> deleteDelegate(AuthzTrans trans, String userName) {
3884 DelegateDAO.Data dd = new DelegateDAO.Data();
3885 final Validator v = new ServiceValidator();
3886 if (v.nullOrBlank("User", userName).err()) {
3887 return Result.err(Status.ERR_BadData,v.errs());
3890 Result<List<DelegateDAO.Data>> ddl;
3891 if ((ddl=ques.delegateDAO.read(trans, dd)).notOKorIsEmpty()) {
3892 return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate");
3894 dd = ddl.value.get(0);
3895 Result<Void> rv = ques.mayUser(trans, dd, Access.write);
3900 return ques.delegateDAO.delete(trans, dd, false);
3904 public Result<DELGS> getDelegatesByUser(AuthzTrans trans, String user) {
3905 final Validator v = new ServiceValidator();
3906 if (v.nullOrBlank("User", user).err()) {
3907 return Result.err(Status.ERR_BadData,v.errs());
3910 DelegateDAO.Data ddd = new DelegateDAO.Data();
3912 ddd.delegate = null;
3913 Result<Void> rv = ques.mayUser(trans, ddd, Access.read);
3915 return Result.err(rv);
3918 TimeTaken tt = trans.start("Get delegates for a user", Env.SUB);
3920 Result<List<DelegateDAO.Data>> dbDelgs = ques.delegateDAO.read(trans, user);
3922 if (dbDelgs.isOKhasData()) {
3923 return mapper.delegate(dbDelgs.value);
3925 return Result.err(Status.ERR_DelegateNotFound,"No Delegate found for [%s]",user);
3933 public Result<DELGS> getDelegatesByDelegate(AuthzTrans trans, String delegate) {
3934 final Validator v = new ServiceValidator();
3935 if (v.nullOrBlank("Delegate", delegate).err()) {
3936 return Result.err(Status.ERR_BadData,v.errs());
3939 DelegateDAO.Data ddd = new DelegateDAO.Data();
3940 ddd.user = delegate;
3941 Result<Void> rv = ques.mayUser(trans, ddd, Access.read);
3943 return Result.err(rv);
3946 TimeTaken tt = trans.start("Get users for a delegate", Env.SUB);
3948 Result<List<DelegateDAO.Data>> dbDelgs = ques.delegateDAO.readByDelegate(trans, delegate);
3950 if (dbDelgs.isOKhasData()) {
3951 return mapper.delegate(dbDelgs.value);
3953 return Result.err(Status.ERR_DelegateNotFound,"Delegate [%s] is not delegating for anyone.",delegate);
3960 /***********************************
3962 ***********************************/
3963 private static final String APPR_FMT = "actor=%s, action=%s, operation=\"%s\", requestor=%s, delegator=%s";
3965 public Result<Void> updateApproval(AuthzTrans trans, APPROVALS approvals) {
3966 Result<List<ApprovalDAO.Data>> rlad = mapper.approvals(approvals);
3968 return Result.err(rlad);
3970 int numApprs = rlad.value.size();
3972 return Result.err(Status.ERR_NoApprovals,"No Approvals sent for Updating");
3974 int numProcessed = 0;
3975 String user = trans.user();
3977 Result<List<ApprovalDAO.Data>> curr;
3978 Lookup<List<ApprovalDAO.Data>> apprByTicket=null;
3979 for (ApprovalDAO.Data updt : rlad.value) {
3980 if (updt.ticket!=null) {
3981 curr = ques.approvalDAO.readByTicket(trans, updt.ticket);
3982 if (curr.isOKhasData()) {
3983 final List<ApprovalDAO.Data> add = curr.value;
3984 // Store a Pre-Lookup
3985 apprByTicket = (trans1, noop) -> add;
3987 } else if (updt.id!=null) {
3988 curr = ques.approvalDAO.read(trans, updt);
3989 } else if (updt.approver!=null) {
3990 curr = ques.approvalDAO.readByApprover(trans, updt.approver);
3992 return Result.err(Status.ERR_BadData,"Approvals need ID, Ticket or Approval data to update");
3995 if (curr.isOKhasData()) {
3996 Map<String, Result<List<DelegateDAO.Data>>> delegateCache = new HashMap<>();
3997 Map<UUID, FutureDAO.Data> futureCache = new HashMap<>();
3998 FutureDAO.Data hasDeleted = new FutureDAO.Data();
4000 for (ApprovalDAO.Data cd : curr.value) {
4001 if ("pending".equals(cd.status)) {
4002 // Check for right record. Need ID, or (Ticket&Trans.User==Appr)
4004 boolean delegatedAction = ques.isDelegated(trans, user, cd.approver, delegateCache);
4005 String delegator = cd.approver;
4006 if (updt.id!=null ||
4007 (updt.ticket!=null && user.equals(cd.approver)) ||
4008 (updt.ticket!=null && delegatedAction)) {
4009 if (updt.ticket.equals(cd.ticket)) {
4010 Changed ch = new Changed();
4011 cd.id = ch.changed(cd.id,updt.id);
4012 // cd.ticket = changed(cd.ticket,updt.ticket);
4013 cd.user = ch.changed(cd.user,updt.user);
4014 cd.approver = ch.changed(cd.approver,updt.approver);
4015 cd.type = ch.changed(cd.type,updt.type);
4016 cd.status = ch.changed(cd.status,updt.status);
4017 cd.memo = ch.changed(cd.memo,updt.memo);
4018 cd.operation = ch.changed(cd.operation,updt.operation);
4019 cd.updated = ch.changed(cd.updated,updt.updated==null?new Date():updt.updated);
4020 if (updt.status.equals("denied")) {
4021 cd.last_notified = null;
4023 if (cd.ticket!=null) {
4024 FutureDAO.Data fdd = futureCache.get(cd.ticket);
4025 if (fdd==null) { // haven't processed ticket yet
4026 Result<FutureDAO.Data> rfdd = ques.futureDAO.readPrimKey(trans, cd.ticket);
4028 fdd = rfdd.value; // null is ok
4032 futureCache.put(cd.ticket, fdd); // processed this Ticket... don't do others on this ticket
4034 if (fdd==hasDeleted) { // YES, by Object
4036 cd.status = "ticketDeleted";
4037 ch.hasChanged(true);
4039 FUTURE_OP fop = FUTURE_OP.toFO(cd.operation);
4041 trans.info().printf("Approval Status %s is not actionable",cd.status);
4042 } else if (apprByTicket!=null) {
4043 Result<OP_STATUS> rv = func.performFutureOp(trans, fop, fdd, apprByTicket,func.urDBLookup);
4047 if (delegatedAction) {
4048 trans.audit().printf(APPR_FMT,user,updt.status,cd.memo,cd.user,delegator);
4050 futureCache.put(cd.ticket, hasDeleted);
4054 ch.hasChanged(true);
4055 trans.audit().printf(APPR_FMT,user,rv.value.desc(),cd.memo,cd.user,delegator);
4056 futureCache.put(cd.ticket, hasDeleted);
4061 trans.info().log(rv.toString());
4068 if (ch.hasChanged()) {
4069 ques.approvalDAO.update(trans, cd, true);
4078 if (numApprs==numProcessed) {
4081 return Result.err(Status.ERR_ActionNotCompleted,numProcessed + " out of " + numApprs + " completed");
4085 private static class Changed {
4086 private boolean hasChanged = false;
4088 public<T> T changed(T src, T proposed) {
4089 if (proposed==null || (src!=null && src.equals(proposed))) {
4096 public void hasChanged(boolean b) {
4100 public boolean hasChanged() {
4106 public Result<APPROVALS> getApprovalsByUser(AuthzTrans trans, String user) {
4107 final Validator v = new ServiceValidator();
4108 if (v.nullOrBlank("User", user).err()) {
4109 return Result.err(Status.ERR_BadData,v.errs());
4112 Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByUser(trans, user);
4114 return mapper.approvals(rapd.value);
4116 return Result.err(rapd);
4121 public Result<APPROVALS> getApprovalsByTicket(AuthzTrans trans, String ticket) {
4122 final Validator v = new ServiceValidator();
4123 if (v.nullOrBlank("Ticket", ticket).err()) {
4124 return Result.err(Status.ERR_BadData,v.errs());
4128 uuid = UUID.fromString(ticket);
4129 } catch (IllegalArgumentException e) {
4130 return Result.err(Status.ERR_BadData,e.getMessage());
4133 Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByTicket(trans, uuid);
4135 return mapper.approvals(rapd.value);
4137 return Result.err(rapd);
4142 public Result<APPROVALS> getApprovalsByApprover(AuthzTrans trans, String approver) {
4143 final Validator v = new ServiceValidator();
4144 if (v.nullOrBlank("Approver", approver).err()) {
4145 return Result.err(Status.ERR_BadData,v.errs());
4148 List<ApprovalDAO.Data> listRapds = new ArrayList<>();
4150 Result<List<ApprovalDAO.Data>> myRapd = ques.approvalDAO.readByApprover(trans, approver);
4151 if (myRapd.notOK()) {
4152 return Result.err(myRapd);
4155 listRapds.addAll(myRapd.value);
4157 Result<List<DelegateDAO.Data>> delegatedFor = ques.delegateDAO.readByDelegate(trans, approver);
4158 if (delegatedFor.isOK()) {
4159 for (DelegateDAO.Data dd : delegatedFor.value) {
4160 if (dd.expires.after(new Date())) {
4161 String delegator = dd.user;
4162 Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByApprover(trans, delegator);
4164 for (ApprovalDAO.Data d : rapd.value) {
4165 if (!d.user.equals(trans.user())) {
4174 return mapper.approvals(listRapds);
4178 * @see org.onap.aaf.auth.service.AuthzService#clearCache(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String)
4181 public Result<Void> cacheClear(AuthzTrans trans, String cname) {
4182 if (ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) {
4183 return ques.clearCache(trans,cname);
4185 return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear",
4186 trans.user(),ROOT_NS,CACHE,cname);
4190 * @see org.onap.aaf.auth.service.AuthzService#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.Integer)
4193 public Result<Void> cacheClear(AuthzTrans trans, String cname, int[] segment) {
4194 if (ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) {
4195 Result<Void> v=null;
4196 for (int i: segment) {
4197 v=ques.cacheClear(trans,cname,i);
4203 return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear",
4204 trans.user(),ROOT_NS,CACHE,cname);
4208 * @see org.onap.aaf.auth.service.AuthzService#dbReset(org.onap.aaf.auth.env.test.AuthzTrans)
4211 public void dbReset(AuthzTrans trans) {
4212 ques.historyDAO.reportPerhapsReset(trans, null);