diff options
author | Instrumental <jcgmisc@stl.gathman.org> | 2018-03-26 13:51:48 -0700 |
---|---|---|
committer | Instrumental <jcgmisc@stl.gathman.org> | 2018-03-26 13:52:07 -0700 |
commit | 71037c39a37d3549dcfe31926832a657744fbe05 (patch) | |
tree | 78911b2b5e86e4e44228f7a27b3a8cd954b7f3e2 /auth/auth-service/src/main | |
parent | a20accc73189d8e5454cd26049c0e6fae75da16f (diff) |
AT&T 2.0.19 Code drop, stage 3
Issue-ID: AAF-197
Change-Id: I8b02cb073ccba318ccaf6ea0276446bdce88fb82
Signed-off-by: Instrumental <jcgmisc@stl.gathman.org>
Diffstat (limited to 'auth/auth-service/src/main')
34 files changed, 12599 insertions, 0 deletions
diff --git a/auth/auth-service/src/main/config/.gitignore b/auth/auth-service/src/main/config/.gitignore new file mode 100644 index 00000000..508486a3 --- /dev/null +++ b/auth/auth-service/src/main/config/.gitignore @@ -0,0 +1,2 @@ +/authAPI.props +/log4j.properties diff --git a/auth/auth-service/src/main/docker/.gitignore b/auth/auth-service/src/main/docker/.gitignore new file mode 100644 index 00000000..508486a3 --- /dev/null +++ b/auth/auth-service/src/main/docker/.gitignore @@ -0,0 +1,2 @@ +/authAPI.props +/log4j.properties diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java new file mode 100644 index 00000000..ad9ccc4a --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java @@ -0,0 +1,227 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service; + +import javax.servlet.Filter; + +import org.onap.aaf.auth.cache.Cache; +import org.onap.aaf.auth.dao.CassAccess; +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.auth.direct.DirectAAFLur; +import org.onap.aaf.auth.direct.DirectAAFUserPass; +import org.onap.aaf.auth.direct.DirectCertIdentity; +import org.onap.aaf.auth.direct.DirectLocatorCreator; +import org.onap.aaf.auth.direct.DirectRegistrar; +import org.onap.aaf.auth.env.AuthzEnv; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.env.AuthzTransFilter; +import org.onap.aaf.auth.org.OrganizationFactory; +import org.onap.aaf.auth.rserv.HttpMethods; +import org.onap.aaf.auth.server.AbsService; +import org.onap.aaf.auth.server.JettyServiceStarter; +import org.onap.aaf.auth.service.api.API_Api; +import org.onap.aaf.auth.service.api.API_Approval; +import org.onap.aaf.auth.service.api.API_Creds; +import org.onap.aaf.auth.service.api.API_Delegate; +import org.onap.aaf.auth.service.api.API_History; +import org.onap.aaf.auth.service.api.API_Mgmt; +import org.onap.aaf.auth.service.api.API_NS; +import org.onap.aaf.auth.service.api.API_Perms; +import org.onap.aaf.auth.service.api.API_Roles; +import org.onap.aaf.auth.service.api.API_User; +import org.onap.aaf.auth.service.api.API_UserRole; +import org.onap.aaf.auth.service.facade.AuthzFacadeFactory; +import org.onap.aaf.auth.service.facade.AuthzFacade_2_0; +import org.onap.aaf.auth.service.mapper.Mapper.API; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.aaf.v2_0.AAFTrustChecker; +import org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.register.Registrant; +import org.onap.aaf.cadi.taf.basic.BasicHttpTaf; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Data; +import org.onap.aaf.misc.env.Env; + +import com.datastax.driver.core.Cluster; + +public class AAF_Service extends AbsService<AuthzEnv,AuthzTrans> { + + private static final String ORGANIZATION = "Organization."; + private static final String DOMAIN = "aaf.att.com"; + +// TODO Add Service Metrics +// private Metric serviceMetric; + public final Question question; +// private final SessionFilter sessionFilter; + private AuthzFacade_2_0 facade; + private AuthzFacade_2_0 facade_XML; + private DirectAAFUserPass directAAFUserPass; + private final Cluster cluster; + //private final OAuthService oauthService; + + /** + * Construct AuthzAPI with all the Context Supporting Routes that Authz needs + * + * @param env + * @param decryptor + * @throws APIException + */ + public AAF_Service( final AuthzEnv env) throws Exception { + super(env.access(), env); + + // Initialize Facade for all uses + AuthzTrans trans = env.newTrans(); + + cluster = org.onap.aaf.auth.dao.CassAccess.cluster(env,null); + + // Need Question for Security purposes (direct User/Authz Query in Filter) + // Start Background Processing + question = new Question(trans, cluster, CassAccess.KEYSPACE, true); + DirectCertIdentity.set(question.certDAO); + + // Have AAFLocator object Create DirectLocators for Location needs + AbsAAFLocator.setCreator(new DirectLocatorCreator(env, question.locateDAO)); + + // Initialize Organizations... otherwise, first pass may miss + int org_size = ORGANIZATION.length(); + for(String n : env.existingStaticSlotNames()) { + if(n.startsWith(ORGANIZATION)) { + OrganizationFactory.obtain(env, n.substring(org_size)); + } + } + + + // For direct Introspection needs. + //oauthService = new OAuthService(trans, question); + + facade = AuthzFacadeFactory.v2_0(env,trans,Data.TYPE.JSON,question); + facade_XML = AuthzFacadeFactory.v2_0(env,trans,Data.TYPE.XML,question); + + directAAFUserPass = new DirectAAFUserPass(trans.env(),question); + + // Print results and cleanup + StringBuilder sb = new StringBuilder(); + trans.auditTrail(0, sb); + if(sb.length()>0)env.init().log(sb); + trans = null; + sb = null; + + //////////////////////////////////////////////////////////////////////////// + // Time Critical + // These will always be evaluated first + //////////////////////////////////////////////////////////////////////// + API_Creds.timeSensitiveInit(env, this, facade,directAAFUserPass); + API_Perms.timeSensitiveInit(this, facade); + //////////////////////////////////////////////////////////////////////// + // Service APIs + //////////////////////////////////////////////////////////////////////// + API_Creds.init(this, facade); + API_UserRole.init(this, facade); + API_Roles.init(this, facade); + API_Perms.init(this, facade); + API_NS.init(this, facade); + API_User.init(this, facade); + API_Delegate.init(this,facade); + API_Approval.init(this, facade); + API_History.init(this, facade); + + //////////////////////////////////////////////////////////////////////// + // Management APIs + //////////////////////////////////////////////////////////////////////// + // There are several APIs around each concept, and it gets a bit too + // long in this class to create. The initialization of these Management + // APIs have therefore been pushed to StandAlone Classes with static + // init functions + API_Mgmt.init(this, facade); + API_Api.init(this, facade); + + } + + @Override + public Filter[] filters() throws CadiException { + try { + return new Filter[] {new AuthzTransFilter(env, null /* no connection to AAF... it is AAF */, + new AAFTrustChecker((Env)env), + new DirectAAFLur(env,question), // Note, this will be assigned by AuthzTransFilter to TrustChecker + //new DirectOAuthTAF(env,question,OAFacadeFactory.directV1_0(oauthService)), + new BasicHttpTaf(env, directAAFUserPass, + DOMAIN,Long.parseLong(env.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)), + false) + )}; + } catch (NumberFormatException e) { + throw new CadiException("Invalid Property information", e); + } + } + + @SuppressWarnings("unchecked") + @Override + public Registrant<AuthzEnv>[] registrants(final int port) throws CadiException { + return new Registrant[] { + new DirectRegistrar(access,question.locateDAO,app_name,app_interface_version,port) + }; + } + + @Override + public void destroy() { + Cache.stopTimer(); + if(cluster!=null) { + cluster.close(); + } + super.destroy(); + } + + + /** + * Setup XML and JSON implementations for each supported Version type + * + * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties + * to do Versions and Content switches + * + */ + public void route(HttpMethods meth, String path, API api, Code code) throws Exception { + String version = "2.0"; + Class<?> respCls = facade.mapper().getClass(api); + if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); + String application = applicationJSON(respCls, version); + + route(env,meth,path,code,application,"application/json;version=2.0","*/*"); + application = applicationXML(respCls, version); + route(env,meth,path,code.clone(facade_XML,false),application,"text/xml;version=2.0"); + } + + /** + * Start up AAF_Service as Jetty Service + */ + public static void main(final String[] args) { + PropAccess propAccess = new PropAccess(args); + try { + AAF_Service service = new AAF_Service(new AuthzEnv(propAccess)); +// service.env().setLog4JNames("log4j.properties","authz","authz|service","audit","init","trace"); + JettyServiceStarter<AuthzEnv,AuthzTrans> jss = new JettyServiceStarter<AuthzEnv,AuthzTrans>(service); + jss.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java new file mode 100644 index 00000000..fa099111 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java @@ -0,0 +1,4245 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service; + +import static org.onap.aaf.auth.env.AuthzTrans.REQD_TYPE.force; +import static org.onap.aaf.auth.env.AuthzTrans.REQD_TYPE.future; +import static org.onap.aaf.auth.layer.Result.OK; +import static org.onap.aaf.auth.rserv.HttpMethods.DELETE; +import static org.onap.aaf.auth.rserv.HttpMethods.GET; +import static org.onap.aaf.auth.rserv.HttpMethods.POST; +import static org.onap.aaf.auth.rserv.HttpMethods.PUT; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.aaf.auth.common.Define; +import org.onap.aaf.auth.dao.DAOException; +import org.onap.aaf.auth.dao.cass.ApprovalDAO; +import org.onap.aaf.auth.dao.cass.CertDAO; +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.dao.cass.DelegateDAO; +import org.onap.aaf.auth.dao.cass.FutureDAO; +import org.onap.aaf.auth.dao.cass.HistoryDAO; +import org.onap.aaf.auth.dao.cass.Namespace; +import org.onap.aaf.auth.dao.cass.NsDAO; +import org.onap.aaf.auth.dao.cass.NsDAO.Data; +import org.onap.aaf.auth.dao.cass.NsSplit; +import org.onap.aaf.auth.dao.cass.NsType; +import org.onap.aaf.auth.dao.cass.PermDAO; +import org.onap.aaf.auth.dao.cass.RoleDAO; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.dao.hl.CassExecutor; +import org.onap.aaf.auth.dao.hl.Function; +import org.onap.aaf.auth.dao.hl.Function.FUTURE_OP; +import org.onap.aaf.auth.dao.hl.Function.Lookup; +import org.onap.aaf.auth.dao.hl.Function.OP_STATUS; +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.auth.dao.hl.Question.Access; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.org.Executor; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.auth.org.Organization.Expiration; +import org.onap.aaf.auth.org.Organization.Identity; +import org.onap.aaf.auth.org.Organization.Policy; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.auth.rserv.doc.ApiDoc; +import org.onap.aaf.auth.service.mapper.Mapper; +import org.onap.aaf.auth.service.mapper.Mapper.API; +import org.onap.aaf.auth.service.validation.ServiceValidator; +import org.onap.aaf.auth.validation.Validator; +import org.onap.aaf.cadi.principal.BasicPrincipal; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.util.Chrono; +import org.onap.aaf.misc.env.util.Split; + +import aaf.v2_0.CredRequest; + +/** + * AuthzCassServiceImpl implements AuthzCassService for + * + * @author Jonathan + * + * @param <NSS> + * @param <PERMS> + * @param <PERMKEY> + * @param <ROLES> + * @param <USERS> + * @param <DELGS> + * @param <REQUEST> + * @param <HISTORY> + * @param <ERR> + * @param <APPROVALS> + */ +public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> + implements AuthzService <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> { + + private Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper; + @Override + public Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper() {return mapper;} + + private static final String ASTERIX = "*"; + private static final String CACHE = "cache"; + private static final String ROOT_NS = Define.ROOT_NS(); + private static final String ROOT_COMPANY = Define.ROOT_COMPANY(); + + private final Question ques; + private final Function func; + + public AuthzCassServiceImpl(AuthzTrans trans, Mapper<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper,Question question) { + this.ques = question; + func = new Function(trans, question); + this.mapper = mapper; + + } + +/*********************************** + * NAMESPACE + ***********************************/ + /** + * createNS + * @throws DAOException + * @see org.onap.aaf.auth.service.AuthzService#createNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @ApiDoc( + method = POST, + path = "/authz/ns", + params = {}, + expectedCode = 201, + errorCodes = { 403,404,406,409 }, + text = { "Namespace consists of: ", + "<ul><li>name - What you want to call this Namespace</li>", + "<li>responsible(s) - Person(s) who receive Notifications and approves Requests ", + "regarding this Namespace. Companies have Policies as to who may take on ", + "this Responsibility. Separate multiple identities with commas</li>", + "<li>admin(s) - Person(s) who are allowed to make changes on the namespace, ", + "including creating Roles, Permissions and Credentials. Separate multiple ", + "identities with commas</li></ul>", + "Note: Namespaces are dot-delimited (i.e. com.myCompany.myApp) and must be ", + "created with parent credentials (i.e. To create com.myCompany.myApp, you must ", + "be an admin of com.myCompany or com" + } + ) + @Override + public Result<Void> createNS(final AuthzTrans trans, REQUEST from, NsType type) { + final Result<Namespace> rnamespace = mapper.ns(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(v.ns(rnamespace).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final Namespace namespace = rnamespace.value; + final Result<NsDAO.Data> parentNs = ques.deriveNs(trans,namespace.name); + if(parentNs.notOK()) { + return Result.err(parentNs); + } + + if(namespace.name.lastIndexOf('.')<0) { // Root Namespace... Function will check if allowed + return func.createNS(trans, namespace, false); + } + + Result<FutureDAO.Data> fd = mapper.future(trans, NsDAO.TABLE,from,namespace,true, + new Mapper.Memo() { + @Override + public String get() { + return "Create Namespace [" + namespace.name + ']'; + } + }, + new MayChange() { + private Result<NsDAO.Data> rnd; + @Override + public Result<?> mayChange() { + if(rnd==null) { + rnd = ques.mayUser(trans, trans.user(), parentNs.value,Access.write); + } + return rnd; + } + }); + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans, fd.value, namespace.name, trans.user(),parentNs.value, FUTURE_OP.C); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "NS [%s] is saved for future processing",namespace.name); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.createNS(trans, namespace, false); + default: + return Result.err(fd); + } + } + + @ApiDoc( + method = POST, + path = "/authz/ns/:ns/admin/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 201, + errorCodes = { 403,404,406,409 }, + text = { "Add an Identity :id to the list of Admins for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" } + ) + @Override + public Result<Void> addAdminNS(AuthzTrans trans, String ns, String id) { + return func.addUserRole(trans, id, ns,Question.ADMIN); + } + + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns/admin/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Remove an Identity :id from the list of Admins for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" } + ) + @Override + public Result<Void> delAdminNS(AuthzTrans trans, String ns, String id) { + return func.delAdmin(trans,ns,id); + } + + @ApiDoc( + method = POST, + path = "/authz/ns/:ns/responsible/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 201, + errorCodes = { 403,404,406,409 }, + text = { "Add an Identity :id to the list of Responsibles for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" } + ) + @Override + public Result<Void> addResponsibleNS(AuthzTrans trans, String ns, String id) { + return func.addUserRole(trans,id,ns,Question.OWNER); + } + + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns/responsible/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Remove an Identity :id to the list of Responsibles for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)", + "Note: A namespace must have at least 1 responsible party" + } + ) + @Override + public Result<Void> delResponsibleNS(AuthzTrans trans, String ns, String id) { + return func.delOwner(trans,ns,id); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#applyModel(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.Object) + */ + @ApiDoc( + method = POST, + path = "/authz/ns/:ns/attrib/:key/:value", + params = { "ns|string|true", + "key|string|true", + "value|string|true"}, + expectedCode = 201, + errorCodes = { 403,404,406,409 }, + text = { + "Create an attribute in the Namespace", + "You must be given direct permission for key by AAF" + } + ) + @Override + public Result<Void> createNsAttrib(AuthzTrans trans, String ns, String key, String value) { + TimeTaken tt = trans.start("Create NsAttrib " + ns + ':' + key + ':' + value, Env.SUB); + try { + // Check inputs + final Validator v = new ServiceValidator(); + if(v.ns(ns).err() || + v.key(key).err() || + v.value(value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Check if exists already + Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns); + if(rlnsd.notOKorIsEmpty()) { + return Result.err(rlnsd); + } + NsDAO.Data nsd = rlnsd.value.get(0); + + // Check for Existence + if(nsd.attrib.get(key)!=null) { + return Result.err(Status.ERR_ConflictAlreadyExists, "NS Property %s:%s exists", ns, key); + } + + // Check if User may put + if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, + ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) { + return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key); + } + + // Add Attrib + nsd.attrib.put(key, value); + ques.nsDAO.dao().attribAdd(trans,ns,key,value); + return Result.ok(); + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authz/ns/attrib/:key", + params = { "key|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { + "Read Attributes for Namespace" + } + ) + @Override + public Result<KEYS> readNsByAttrib(AuthzTrans trans, String key) { + // Check inputs + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Key",key).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // May Read + if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, + ":"+trans.org().getDomain()+".*:"+key, Question.READ)) { + return Result.err(Status.ERR_Denied,"%s may not read NS by Attrib '%s'",trans.user(),key); + } + + Result<Set<String>> rsd = ques.nsDAO.dao().readNsByAttrib(trans, key); + if(rsd.notOK()) { + return Result.err(rsd); + } + return mapper().keys(rsd.value); + } + + + @ApiDoc( + method = PUT, + path = "/authz/ns/:ns/attrib/:key/:value", + params = { "ns|string|true", + "key|string|true"}, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { + "Update Value on an existing attribute in the Namespace", + "You must be given direct permission for key by AAF" + } + ) + @Override + public Result<?> updateNsAttrib(AuthzTrans trans, String ns, String key, String value) { + TimeTaken tt = trans.start("Update NsAttrib " + ns + ':' + key + ':' + value, Env.SUB); + try { + // Check inputs + final Validator v = new ServiceValidator(); + if(v.ns(ns).err() || + v.key(key).err() || + v.value(value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Check if exists already (NS must exist) + Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns); + if(rlnsd.notOKorIsEmpty()) { + return Result.err(rlnsd); + } + NsDAO.Data nsd = rlnsd.value.get(0); + + // Check for Existence + if(nsd.attrib.get(key)==null) { + return Result.err(Status.ERR_NotFound, "NS Property %s:%s exists", ns, key); + } + + // Check if User may put + if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, + ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) { + return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key); + } + + // Add Attrib + nsd.attrib.put(key, value); + + return ques.nsDAO.update(trans,nsd); + + } finally { + tt.done(); + } + } + + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns/attrib/:key", + params = { "ns|string|true", + "key|string|true"}, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { + "Delete an attribute in the Namespace", + "You must be given direct permission for key by AAF" + } + ) + @Override + public Result<Void> deleteNsAttrib(AuthzTrans trans, String ns, String key) { + TimeTaken tt = trans.start("Delete NsAttrib " + ns + ':' + key, Env.SUB); + try { + // Check inputs + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS",ns).err() || + v.nullOrBlank("Key",key).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Check if exists already + Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns); + if(rlnsd.notOKorIsEmpty()) { + return Result.err(rlnsd); + } + NsDAO.Data nsd = rlnsd.value.get(0); + + // Check for Existence + if(nsd.attrib.get(key)==null) { + return Result.err(Status.ERR_NotFound, "NS Property [%s:%s] does not exist", ns, key); + } + + // Check if User may del + if(!ques.isGranted(trans, trans.user(), ROOT_NS, "attrib", ":" + ROOT_COMPANY + ".*:"+key, Access.write.name())) { + return Result.err(Status.ERR_Denied, "%s may not delete NS Attrib [%s:%s]", trans.user(),ns, key); + } + + // Add Attrib + nsd.attrib.remove(key); + ques.nsDAO.dao().attribRemove(trans,ns,key); + return Result.ok(); + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authz/nss/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { + "Lists the Admin(s), Responsible Party(s), Role(s), Permission(s)", + "Credential(s) and Expiration of Credential(s) in Namespace :id", + } + ) + @Override + public Result<NSS> getNSbyName(AuthzTrans trans, String ns) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS", ns).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, ns); + if(rlnd.isOK()) { + if(rlnd.isEmpty()) { + return Result.err(Status.ERR_NotFound, "No data found for %s",ns); + } + Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + + Namespace namespace = new Namespace(rnd.value); + Result<List<String>> rd = func.getOwners(trans, namespace.name, false); + if(rd.isOK()) { + namespace.owner = rd.value; + } + rd = func.getAdmins(trans, namespace.name, false); + if(rd.isOK()) { + namespace.admin = rd.value; + } + + NSS nss = mapper.newInstance(API.NSS); + return mapper.nss(trans, namespace, nss); + } else { + return Result.err(rlnd); + } + } + + @ApiDoc( + method = GET, + path = "/authz/nss/admin/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Namespaces where Identity :id is an Admin", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" + } + ) + @Override + public Result<NSS> getNSbyAdmin(AuthzTrans trans, String user, boolean full) { + final Validator v = new ServiceValidator(); + if (v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData, v.errs()); + } + + Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".admin", full); + if(rn.notOK()) { + return Result.err(rn); + } + if (rn.isEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] is not an admin for any namespaces",user); + } + NSS nss = mapper.newInstance(API.NSS); + // Note: "loadNamespace" already validates view of Namespace + return mapper.nss(trans, rn.value, nss); + + } + + @ApiDoc( + method = GET, + path = "/authz/nss/either/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Namespaces where Identity :id is either an Admin or an Owner", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" + } + ) + @Override + public Result<NSS> getNSbyEither(AuthzTrans trans, String user, boolean full) { + final Validator v = new ServiceValidator(); + if (v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData, v.errs()); + } + + Result<Collection<Namespace>> rn = loadNamepace(trans, user, null, full); + if(rn.notOK()) { + return Result.err(rn); + } + if (rn.isEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] is not an admin or owner for any namespaces",user); + } + NSS nss = mapper.newInstance(API.NSS); + // Note: "loadNamespace" already validates view of Namespace + return mapper.nss(trans, rn.value, nss); + } + + private Result<Collection<Namespace>> loadNamepace(AuthzTrans trans, String user, String endsWith, boolean full) { + Result<List<UserRoleDAO.Data>> urd = ques.userRoleDAO.readByUser(trans, user); + if(urd.notOKorIsEmpty()) { + return Result.err(urd); + } + Map<String, Namespace> lm = new HashMap<String,Namespace>(); + Map<String, Namespace> other = full || endsWith==null?null:new TreeMap<String,Namespace>(); + for(UserRoleDAO.Data urdd : urd.value) { + if(full) { + if(endsWith==null || urdd.role.endsWith(endsWith)) { + RoleDAO.Data rd = RoleDAO.Data.decode(urdd); + Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read); + if(nsd.isOK()) { + Namespace namespace = lm.get(nsd.value.name); + if(namespace==null) { + namespace = new Namespace(nsd.value); + lm.put(namespace.name,namespace); + } + Result<List<String>> rls = func.getAdmins(trans, namespace.name, false); + if(rls.isOK()) { + namespace.admin=rls.value; + } + + rls = func.getOwners(trans, namespace.name, false); + if(rls.isOK()) { + namespace.owner=rls.value; + } + } + } + } else { // Shortened version. Only Namespace Info available from Role. + if(Question.ADMIN.equals(urdd.rname) || Question.OWNER.equals(urdd.rname)) { + RoleDAO.Data rd = RoleDAO.Data.decode(urdd); + Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read); + if(nsd.isOK()) { + Namespace namespace = lm.get(nsd.value.name); + if(namespace==null) { + if(other!=null) { + namespace = other.remove(nsd.value.name); + } + if(namespace==null) { + namespace = new Namespace(nsd.value); + namespace.admin=new ArrayList<String>(); + namespace.owner=new ArrayList<String>(); + } + if(endsWith==null || urdd.role.endsWith(endsWith)) { + lm.put(namespace.name,namespace); + } else { + other.put(namespace.name,namespace); + } + } + if(Question.OWNER.equals(urdd.rname)) { + namespace.owner.add(urdd.user); + } else { + namespace.admin.add(urdd.user); + } + } + } + } + } + return Result.ok(lm.values()); + } + + @ApiDoc( + method = GET, + path = "/authz/nss/responsible/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Namespaces where Identity :id is a Responsible Party", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" + } + ) + @Override + public Result<NSS> getNSbyResponsible(AuthzTrans trans, String user, boolean full) { + final Validator v = new ServiceValidator(); + if (v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData, v.errs()); + } + Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".owner",full); + if(rn.notOK()) { + return Result.err(rn); + } + if (rn.isEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] is not an owner for any namespaces",user); + } + NSS nss = mapper.newInstance(API.NSS); + // Note: "loadNamespace" prevalidates + return mapper.nss(trans, rn.value, nss); + } + + @ApiDoc( + method = GET, + path = "/authz/nss/children/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Child Namespaces of Namespace :id", + "Note: This is not a cached read" + } + ) + @Override + public Result<NSS> getNSsChildren(AuthzTrans trans, String parent) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS", parent).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<NsDAO.Data> rnd = ques.deriveNs(trans, parent); + if(rnd.notOK()) { + return Result.err(rnd); + } + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + Set<Namespace> lm = new HashSet<Namespace>(); + Result<List<NsDAO.Data>> rlnd = ques.nsDAO.dao().getChildren(trans, parent); + if(rlnd.isOK()) { + if(rlnd.isEmpty()) { + return Result.err(Status.ERR_NotFound, "No data found for %s",parent); + } + for(NsDAO.Data ndd : rlnd.value) { + Namespace namespace = new Namespace(ndd); + Result<List<String>> rls = func.getAdmins(trans, namespace.name, false); + if(rls.isOK()) { + namespace.admin=rls.value; + } + + rls = func.getOwners(trans, namespace.name, false); + if(rls.isOK()) { + namespace.owner=rls.value; + } + + lm.add(namespace); + } + NSS nss = mapper.newInstance(API.NSS); + return mapper.nss(trans,lm, nss); + } else { + return Result.err(rlnd); + } + } + + + @ApiDoc( + method = PUT, + path = "/authz/ns", + params = {}, + expectedCode = 200, + errorCodes = { 403,404,406 }, + text = { "Replace the Current Description of a Namespace with a new one" + } + ) + @Override + public Result<Void> updateNsDescription(AuthzTrans trans, REQUEST from) { + final Result<Namespace> nsd = mapper.ns(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(v.ns(nsd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + if(v.nullOrBlank("description", nsd.value.description).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Namespace namespace = nsd.value; + Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, namespace.name); + + if(rlnd.notOKorIsEmpty()) { + return Result.err(Status.ERR_NotFound, "Namespace [%s] does not exist",namespace.name); + } + + if (ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change %s",namespace.name); + } + + Result<Void> rdr = ques.nsDAO.dao().addDescription(trans, namespace.name, namespace.description); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + } + + /** + * deleteNS + * @throws DAOException + * @see org.onap.aaf.auth.service.AuthzService#deleteNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns", + params = { "ns|string|true" }, + expectedCode = 200, + errorCodes = { 403,404,424 }, + text = { "Delete the Namespace :ns. Namespaces cannot normally be deleted when there ", + "are still credentials associated with them, but they can be deleted by setting ", + "the \"force\" property. To do this: Add 'force=true' as a query parameter", + "<p>WARNING: Using force will delete all credentials attached to this namespace. Use with care.</p>" + + "if the \"force\" property is set to 'force=move', then Permissions and Roles are not deleted," + + "but are retained, and assigned to the Parent Namespace. 'force=move' is not permitted " + + "at or below Application Scope" + } + ) + @Override + public Result<Void> deleteNS(AuthzTrans trans, String ns) { + return func.deleteNS(trans, ns); + } + + +/*********************************** + * PERM + ***********************************/ + + /* + * (non-Javadoc) + * @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) + */ + @ApiDoc( + method = POST, + path = "/authz/perm", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { "Permission consists of:", + "<ul><li>type - a Namespace qualified identifier specifying what kind of resource " + + "is being protected</li>", + "<li>instance - a key, possibly multi-dimensional, that identifies a specific " + + " instance of the type</li>", + "<li>action - what kind of action is allowed</li></ul>", + "Note: instance and action can be an *" + } + ) + @Override + public Result<Void> createPerm(final AuthzTrans trans,REQUEST rreq) { + final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq); + final ServiceValidator v = new ServiceValidator(); + if(v.perm(newPd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, newPd.value,false, + new Mapper.Memo() { + @Override + public String get() { + return "Create Permission [" + + newPd.value.fullType() + '|' + + newPd.value.instance + '|' + + newPd.value.action + ']'; + } + }, + new MayChange() { + private Result<NsDAO.Data> nsd; + @Override + public Result<?> mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), newPd.value, Access.write); + } + return nsd; + } + }); + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, newPd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans,fd.value, + newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action, + trans.user(), + nsr.value.get(0), + FUTURE_OP.C); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", + newPd.value.ns, + newPd.value.type, + newPd.value.instance, + newPd.value.action); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.createPerm(trans, newPd.value, true); + default: + return Result.err(fd); + } + } + + @ApiDoc( + method = GET, + path = "/authz/perms/:type", + params = {"type|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match the :type element of the key" } + ) + @Override + public Result<PERMS> getPermsByType(AuthzTrans trans, final String permType) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("PermType", permType).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<List<PermDAO.Data>> rlpd = ques.getPermsByType(trans, permType); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + +// We don't have instance & action for mayUserView... do we want to loop through all returned here as well as in mapper? +// Result<NsDAO.Data> r; +// if((r = ques.mayUserViewPerm(trans, trans.user(), permType)).notOK())return Result.err(r); + + PERMS perms = mapper.newInstance(API.PERMS); + if(!rlpd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value, perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/:type/:instance/:action", + params = {"type|string|true", + "instance|string|true", + "action|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List Permissions that match key; :type, :instance and :action" } + ) + @Override + public Result<PERMS> getPermsByName(AuthzTrans trans, String type, String instance, String action) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("PermType", type).err() + || v.nullOrBlank("PermInstance", instance).err() + || v.nullOrBlank("PermAction", action).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<List<PermDAO.Data>> rlpd = ques.getPermsByName(trans, type, instance, action); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + if(!rlpd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value, perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/user/:user", + params = {"user|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match user :user", + "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>"} + ) + @Override + public Result<PERMS> getPermsByUser(AuthzTrans trans, String user) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user, + trans.requested(force)); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + + if(rlpd.isEmpty()) { + return Result.ok(perms); + } + // Note: Mapper will restrict what can be viewed + // if user is the same as that which is looked up, no filtering is required + return mapper.perms(trans, rlpd.value, + perms, + !user.equals(trans.user())); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/user/:user/scope/:scope", + params = {"user|string|true","scope|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match user :user, filtered by NS (Scope)", + "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>", + "<p>'scope' must be expressed as NSs separated by ':'</p>" + } + ) + @Override + public Result<PERMS> getPermsByUserScope(AuthzTrans trans, String user, String[] scopes) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user, trans.requested(force)); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + + if(rlpd.isEmpty()) { + return Result.ok(perms); + } + // Note: Mapper will restrict what can be viewed + // if user is the same as that which is looked up, no filtering is required + return mapper.perms(trans, rlpd.value, + perms, + scopes, + !user.equals(trans.user())); + } + + @ApiDoc( + method = POST, + path = "/authz/perms/user/:user", + params = {"user|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match user :user", + "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>", + "", + "Present Queries as one or more Permissions (see ContentType Links below for format).", + "", + "If the Caller is Granted this specific Permission, and the Permission is valid", + " for the User, it will be included in response Permissions, along with", + " all the normal permissions on the 'GET' version of this call. If it is not", + " valid, or Caller does not have permission to see, it will be removed from the list", + "", + " *Note: This design allows you to make one call for all expected permissions", + " The permission to be included MUST be:", + " <user namespace>.access|:<ns|role|perm>[:key]|<create|read|write>", + " examples:", + " com.att.myns.access|:ns|write", + " com.att.myns.access|:role:myrole|create", + " com.att.myns.access|:perm:mytype:myinstance:myaction|read", + "" + } + ) + @Override + public Result<PERMS> getPermsByUser(AuthzTrans trans, PERMS _perms, String user) { + PERMS perms = _perms; + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + ////////////// + Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user,trans.requested(force)); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + /*//TODO + 1) See if allowed to query + 2) See if User is allowed + */ + Result<List<PermDAO.Data>> in = mapper.perms(trans, perms); + if(in.isOKhasData()) { + List<PermDAO.Data> out = rlpd.value; + boolean ok; + for(PermDAO.Data pdd : in.value) { + ok = false; + if("access".equals(pdd.type)) { + Access access = Access.valueOf(pdd.action); + String[] mdkey = Split.splitTrim(':',pdd.instance); + if(mdkey.length>1) { + String type = mdkey[1]; + if("role".equals(type)) { + if(mdkey.length>2) { + RoleDAO.Data rdd = new RoleDAO.Data(); + rdd.ns=pdd.ns; + rdd.name=mdkey[2]; + ok = ques.mayUser(trans, trans.user(), rdd, Access.read).isOK() && ques.mayUser(trans, user, rdd , access).isOK(); + } + } else if("perm".equals(type)) { + if(mdkey.length>4) { // also need instance/action + PermDAO.Data p = new PermDAO.Data(); + p.ns=pdd.ns; + p.type=mdkey[2]; + p.instance=mdkey[3]; + p.action=mdkey[4]; + ok = ques.mayUser(trans, trans.user(), p, Access.read).isOK() && ques.mayUser(trans, user, p , access).isOK(); + } + } else if("ns".equals(type)) { + NsDAO.Data ndd = new NsDAO.Data(); + ndd.name=pdd.ns; + ok = ques.mayUser(trans, trans.user(), ndd, Access.read).isOK() && ques.mayUser(trans, user, ndd , access).isOK(); + } + } + } + if(ok) { + out.add(pdd); + } + } + } + + perms = mapper.newInstance(API.PERMS); + if(rlpd.isEmpty()) { + return Result.ok(perms); + } + // Note: Mapper will restrict what can be viewed + // if user is the same as that which is looked up, no filtering is required + return mapper.perms(trans, rlpd.value, + perms, + !user.equals(trans.user())); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/role/:role", + params = {"role|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that are granted to :role" } + ) + @Override + public Result<PERMS> getPermsByRole(AuthzTrans trans,String role) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Role", role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques,role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + Result<NsDAO.Data> r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); + if(r.notOK()) { + return Result.err(r); + } + + PERMS perms = mapper.newInstance(API.PERMS); + + Result<List<PermDAO.Data>> rlpd = ques.getPermsByRole(trans, role, trans.requested(force)); + if(rlpd.isOKhasData()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value, perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/ns/:ns", + params = {"ns|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that are in Namespace :ns" } + ) + @Override + public Result<PERMS> getPermsByNS(AuthzTrans trans,String ns) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS", ns).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<NsDAO.Data> rnd = ques.deriveNs(trans, ns); + if(rnd.notOK()) { + return Result.err(rnd); + } + + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + Result<List<PermDAO.Data>> rlpd = ques.permDAO.readNS(trans, ns); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + if(!rlpd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value,perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = PUT, + path = "/authz/perm/:type/:instance/:action", + params = {"type|string|true", + "instance|string|true", + "action|string|true"}, + expectedCode = 200, + errorCodes = { 404,406, 409 }, + text = { "Rename the Permission referenced by :type :instance :action, and " + + "rename (copy/delete) to the Permission described in PermRequest" } + ) + @Override + public Result<Void> renamePerm(final AuthzTrans trans,REQUEST rreq, String origType, String origInstance, String origAction) { + final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq); + final ServiceValidator v = new ServiceValidator(); + if(v.perm(newPd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + if (ques.mayUser(trans, trans.user(), newPd.value,Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]", + newPd.value.ns,newPd.value.type,newPd.value.instance,newPd.value.action); + } + + Result<NsSplit> nss = ques.deriveNsSplit(trans, origType); + Result<List<PermDAO.Data>> origRlpd = ques.permDAO.read(trans, nss.value.ns, nss.value.name, origInstance, origAction); + + if(origRlpd.notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, + "Permission [%s|%s|%s] does not exist", + origType,origInstance,origAction); + } + + PermDAO.Data origPd = origRlpd.value.get(0); + + if (!origPd.ns.equals(newPd.value.ns)) { + return Result.err(Status.ERR_Denied, "Cannot change namespace with rename command. " + + "<new type> must start with [" + origPd.ns + "]"); + } + + if ( origPd.type.equals(newPd.value.type) && + origPd.action.equals(newPd.value.action) && + origPd.instance.equals(newPd.value.instance) ) { + return Result.err(Status.ERR_ConflictAlreadyExists, "New Permission must be different than original permission"); + } + + Set<String> origRoles = origPd.roles(false); + if (!origRoles.isEmpty()) { + Set<String> roles = newPd.value.roles(true); + for (String role : origPd.roles) { + roles.add(role); + } + } + + newPd.value.description = origPd.description; + + Result<Void> rv = null; + + rv = func.createPerm(trans, newPd.value, false); + if (rv.isOK()) { + rv = func.deletePerm(trans, origPd, true, false); + } + return rv; + } + + @ApiDoc( + method = PUT, + path = "/authz/perm", + params = {}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "Add Description Data to Perm" } + ) + @Override + public Result<Void> updatePermDescription(AuthzTrans trans, REQUEST from) { + final Result<PermDAO.Data> pd = mapper.perm(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(v.perm(pd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + if(v.nullOrBlank("description", pd.value.description).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final PermDAO.Data perm = pd.value; + if(ques.permDAO.read(trans, perm.ns, perm.type, perm.instance,perm.action).notOKorIsEmpty()) { + return Result.err(Status.ERR_NotFound, "Permission [%s.%s|%s|%s] does not exist", + perm.ns,perm.type,perm.instance,perm.action); + } + + if (ques.mayUser(trans, trans.user(), perm, Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]", + perm.ns,perm.type,perm.instance,perm.action); + } + + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Result<Void> rdr = ques.permDAO.addDescription(trans, perm.ns, perm.type, perm.instance, + perm.action, perm.description); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + + } + + @ApiDoc( + method = PUT, + path = "/authz/role/perm", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { "Set a permission's roles to roles given" } + ) + + @Override + public Result<Void> resetPermRoles(final AuthzTrans trans, REQUEST rreq) { + final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq); + if(updt.notOKorIsEmpty()) { + return Result.err(updt); + } + + final ServiceValidator v = new ServiceValidator(); + if(v.perm(updt).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write); + if (nsd.notOK()) { + return Result.err(nsd); + } + + // Read full set to get CURRENT values + Result<List<PermDAO.Data>> rcurr = ques.permDAO.read(trans, + updt.value.ns, + updt.value.type, + updt.value.instance, + updt.value.action); + + if(rcurr.notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, + "Permission [%s.%s|%s|%s] does not exist", + updt.value.ns,updt.value.type,updt.value.instance,updt.value.action); + } + + // Create a set of Update Roles, which are in Internal Format + Set<String> updtRoles = new HashSet<String>(); + Result<NsSplit> nss; + for(String role : updt.value.roles(false)) { + nss = ques.deriveNsSplit(trans, role); + if(nss.isOK()) { + updtRoles.add(nss.value.ns + '|' + nss.value.name); + } else { + trans.error().log(nss.errorString()); + } + } + + Result<Void> rv = null; + + for(PermDAO.Data curr : rcurr.value) { + Set<String> currRoles = curr.roles(false); + // must add roles to this perm, and add this perm to each role + // in the update, but not in the current + for (String role : updtRoles) { + if (!currRoles.contains(role)) { + Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role); + if(key.isOKhasData()) { + Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, key.value); + if(rrd.isOKhasData()) { + for(RoleDAO.Data r : rrd.value) { + rv = func.addPermToRole(trans, r, curr, false); + if (rv.notOK() && rv.status!=Result.ERR_ConflictAlreadyExists) { + return Result.err(rv); + } + } + } else { + return Result.err(rrd); + } + } + } + } + // similarly, must delete roles from this perm, and delete this perm from each role + // in the update, but not in the current + for (String role : currRoles) { + if (!updtRoles.contains(role)) { + Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role); + if(key.isOKhasData()) { + Result<List<RoleDAO.Data>> rdd = ques.roleDAO.read(trans, key.value); + if(rdd.isOKhasData()) { + for(RoleDAO.Data r : rdd.value) { + rv = func.delPermFromRole(trans, r, curr, true); + if (rv.notOK() && rv.status!=Status.ERR_PermissionNotFound) { + return Result.err(rv); + } + } + } + } + } + } + } + return rv==null?Result.ok():rv; + } + + @ApiDoc( + method = DELETE, + path = "/authz/perm", + params = {}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "Delete the Permission referenced by PermKey.", + "You cannot normally delete a permission which is still granted to roles,", + "however the \"force\" property allows you to do just that. To do this: Add", + "'force=true' as a query parameter.", + "<p>WARNING: Using force will ungrant this permission from all roles. Use with care.</p>" } + ) + @Override + public Result<Void> deletePerm(final AuthzTrans trans, REQUEST from) { + Result<PermDAO.Data> pd = mapper.perm(trans, from); + if(pd.notOK()) { + return Result.err(pd); + } + final ServiceValidator v = new ServiceValidator(); + if(v.nullOrBlank(pd.value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final PermDAO.Data perm = pd.value; + if (ques.permDAO.read(trans, perm).notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, "Permission [%s.%s|%s|%s] does not exist", + perm.ns,perm.type,perm.instance,perm.action ); + } + + Result<FutureDAO.Data> fd = mapper.future(trans,PermDAO.TABLE,from,perm,false, + new Mapper.Memo() { + @Override + public String get() { + return "Delete Permission [" + perm.fullPerm() + ']'; + } + }, + new MayChange() { + private Result<NsDAO.Data> nsd; + @Override + public Result<?> mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), perm, Access.write); + } + return nsd; + } + }); + + switch(fd.status) { + case OK: + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, perm.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Result<String> rfc = func.createFuture(trans, fd.value, + perm.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Perm Deletion [%s] is saved for future processing",perm.encode()); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.deletePerm(trans,perm,trans.requested(force), false); + default: + return Result.err(fd); + } + } + + @ApiDoc( + method = DELETE, + path = "/authz/perm/:name/:type/:action", + params = {"type|string|true", + "instance|string|true", + "action|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "Delete the Permission referenced by :type :instance :action", + "You cannot normally delete a permission which is still granted to roles,", + "however the \"force\" property allows you to do just that. To do this: Add", + "'force=true' as a query parameter", + "<p>WARNING: Using force will ungrant this permission from all roles. Use with care.</p>"} + ) + @Override + public Result<Void> deletePerm(AuthzTrans trans, String type, String instance, String action) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Type",type) + .nullOrBlank("Instance",instance) + .nullOrBlank("Action",action) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<PermDAO.Data> pd = ques.permFrom(trans, type, instance, action); + if(pd.isOK()) { + return func.deletePerm(trans, pd.value, trans.requested(force), false); + } else { + return Result.err(pd); + } + } + +/*********************************** + * ROLE + ***********************************/ + @ApiDoc( + method = POST, + path = "/authz/role", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { + + "Roles are part of Namespaces", + "Examples:", + "<ul><li>org.onap.aaf - The team that created and maintains AAF</li>", + "Roles do not include implied permissions for an App. Instead, they contain explicit Granted Permissions by any Namespace in AAF (See Permissions)", + "Restrictions on Role Names:", + "<ul><li>Must start with valid Namespace name, terminated by . (dot/period)</li>", + "<li>Allowed Characters are a-zA-Z0-9._-</li>", + "<li>role names are Case Sensitive</li></ul>", + "The right questions to ask for defining and populating a Role in AAF, therefore, are:", + "<ul><li>'What Job Function does this represent?'</li>", + "<li>'Does this person perform this Job Function?'</li></ul>" } + ) + + @Override + public Result<Void> createRole(final AuthzTrans trans, REQUEST from) { + final Result<RoleDAO.Data> rd = mapper.role(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(v.role(rd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final RoleDAO.Data role = rd.value; + if(ques.roleDAO.read(trans, role.ns, role.name).isOKhasData()) { + return Result.err(Status.ERR_ConflictAlreadyExists, "Role [" + role.fullName() + "] already exists"); + } + + Result<FutureDAO.Data> fd = mapper.future(trans,RoleDAO.TABLE,from,role,false, + new Mapper.Memo() { + @Override + public String get() { + return "Create Role [" + + rd.value.fullName() + + ']'; + } + }, + new MayChange() { + private Result<NsDAO.Data> nsd; + @Override + public Result<?> mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), role, Access.write); + } + return nsd; + } + }); + + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans, fd.value, + role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.C); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Role [%s.%s] is saved for future processing", + rd.value.ns, + rd.value.name); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + Result<RoleDAO.Data> rdr = ques.roleDAO.create(trans, role); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + default: + return Result.err(fd); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#getRolesByName(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ + @ApiDoc( + method = GET, + path = "/authz/roles/:role", + params = {"role|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "List Roles that match :role", + "Note: You must have permission to see any given role" + } + ) + @Override + public Result<ROLES> getRolesByName(AuthzTrans trans, String role) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Role", role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Determine if User can ask this question + Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role); + if(rrdd.isOKhasData()) { + Result<NsDAO.Data> r; + if((r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read)).notOK()) { + return Result.err(r); + } + } else { + return Result.err(rrdd); + } + + // Look up data + Result<List<RoleDAO.Data>> rlrd = ques.getRolesByName(trans, role); + if(rlrd.isOK()) { + // Note: Mapper will restrict what can be viewed + ROLES roles = mapper.newInstance(API.ROLES); + return mapper.roles(trans, rlrd.value, roles, true); + } else { + return Result.err(rlrd); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ + @ApiDoc( + method = GET, + path = "/authz/roles/user/:name", + params = {"name|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "List all Roles that match user :name", + "'user' must be expressed as full identity (ex: id@full.domain.com)", + "Note: You must have permission to see any given role" + } + ) + + @Override + public Result<ROLES> getRolesByUser(AuthzTrans trans, String user) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + ROLES roles = mapper.newInstance(API.ROLES); + // Get list of roles per user, then add to Roles as we go + Result<List<RoleDAO.Data>> rlrd; + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user); + if(rlurd.isOKhasData()) { + for(UserRoleDAO.Data urd : rlurd.value ) { + rlrd = ques.roleDAO.read(trans, urd.ns,urd.rname); + // Note: Mapper will restrict what can be viewed + // if user is the same as that which is looked up, no filtering is required + if(rlrd.isOKhasData()) { + mapper.roles(trans, rlrd.value,roles, !user.equals(trans.user())); + } + } + } + return Result.ok(roles); + } + + /* + * (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ + @ApiDoc( + method = GET, + path = "/authz/roles/ns/:ns", + params = {"ns|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "List all Roles for the Namespace :ns", + "Note: You must have permission to see any given role" + } + ) + + @Override + public Result<ROLES> getRolesByNS(AuthzTrans trans, String ns) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS", ns).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // check if user is allowed to view NS + Result<NsDAO.Data> rnsd = ques.deriveNs(trans, ns); + if(rnsd.notOK()) { + return Result.err(rnsd); + } + rnsd = ques.mayUser(trans, trans.user(), rnsd.value, Access.read); + if(rnsd.notOK()) { + return Result.err(rnsd); + } + + TimeTaken tt = trans.start("MAP Roles by NS to Roles", Env.SUB); + try { + ROLES roles = mapper.newInstance(API.ROLES); + // Get list of roles per user, then add to Roles as we go + Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readNS(trans, ns); + if(rlrd.isOK()) { + if(!rlrd.isEmpty()) { + // Note: Mapper doesn't need to restrict what can be viewed, because we did it already. + mapper.roles(trans,rlrd.value,roles,false); + } + return Result.ok(roles); + } else { + return Result.err(rlrd); + } + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#getRolesByNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ + @ApiDoc( + method = GET, + path = "/authz/roles/name/:name", + params = {"name|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "List all Roles for only the Name of Role (without Namespace)", + "Note: You must have permission to see any given role" + } + ) + @Override + public Result<ROLES> getRolesByNameOnly(AuthzTrans trans, String name) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Name", name).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // User Mapper to make sure user is allowed to view NS + + TimeTaken tt = trans.start("MAP Roles by Name to Roles", Env.SUB); + try { + ROLES roles = mapper.newInstance(API.ROLES); + // Get list of roles per user, then add to Roles as we go + Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readName(trans, name); + if(rlrd.isOK()) { + if(!rlrd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + mapper.roles(trans,rlrd.value,roles,true); + } + return Result.ok(roles); + } else { + return Result.err(rlrd); + } + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authz/roles/perm/:type/:instance/:action", + params = {"type|string|true", + "instance|string|true", + "action|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "Find all Roles containing the given Permission." + + "Permission consists of:", + "<ul><li>type - a Namespace qualified identifier specifying what kind of resource " + + "is being protected</li>", + "<li>instance - a key, possibly multi-dimensional, that identifies a specific " + + " instance of the type</li>", + "<li>action - what kind of action is allowed</li></ul>", + "Notes: instance and action can be an *", + " You must have permission to see any given role" + } + ) + + @Override + public Result<ROLES> getRolesByPerm(AuthzTrans trans, String type, String instance, String action) { + final Validator v = new ServiceValidator(); + if(v.permType(type,null) + .permInstance(instance) + .permAction(action) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + TimeTaken tt = trans.start("Map Perm Roles Roles", Env.SUB); + try { + ROLES roles = mapper.newInstance(API.ROLES); + // Get list of roles per user, then add to Roles as we go + Result<NsSplit> nsSplit = ques.deriveNsSplit(trans, type); + if(nsSplit.isOK()) { + PermDAO.Data pdd = new PermDAO.Data(nsSplit.value, instance, action); + Result<?> res; + if((res=ques.mayUser(trans, trans.user(), pdd, Question.Access.read)).notOK()) { + return Result.err(res); + } + + Result<List<PermDAO.Data>> pdlr = ques.permDAO.read(trans, pdd); + if(pdlr.isOK())for(PermDAO.Data pd : pdlr.value) { + Result<List<RoleDAO.Data>> rlrd; + for(String r : pd.roles) { + Result<String[]> rs = RoleDAO.Data.decodeToArray(trans, ques, r); + if(rs.isOK()) { + rlrd = ques.roleDAO.read(trans, rs.value[0],rs.value[1]); + // Note: Mapper will restrict what can be viewed + if(rlrd.isOKhasData()) { + mapper.roles(trans,rlrd.value,roles,true); + } + } + } + } + } + return Result.ok(roles); + } finally { + tt.done(); + } + } + + @ApiDoc( + method = PUT, + path = "/authz/role", + params = {}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "Add Description Data to a Role" } + ) + + @Override + public Result<Void> updateRoleDescription(AuthzTrans trans, REQUEST from) { + final Result<RoleDAO.Data> rd = mapper.role(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(v.role(rd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } { + if(v.nullOrBlank("description", rd.value.description).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + } + final RoleDAO.Data role = rd.value; + if(ques.roleDAO.read(trans, role.ns, role.name).notOKorIsEmpty()) { + return Result.err(Status.ERR_NotFound, "Role [" + role.fullName() + "] does not exist"); + } + + if (ques.mayUser(trans, trans.user(), role, Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change " + role.fullName()); + } + + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Result<Void> rdr = ques.roleDAO.addDescription(trans, role.ns, role.name, role.description); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + + } + + @ApiDoc( + method = POST, + path = "/authz/role/perm", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { "Grant a Permission to a Role", + "Permission consists of:", + "<ul><li>type - a Namespace qualified identifier specifying what kind of resource " + + "is being protected</li>", + "<li>instance - a key, possibly multi-dimensional, that identifies a specific " + + " instance of the type</li>", + "<li>action - what kind of action is allowed</li></ul>", + "Note: instance and action can be an *", + "Note: Using the \"force\" property will create the Permission, if it doesn't exist AND the requesting " + + " ID is allowed to create. It will then grant", + " the permission to the role in one step. To do this: add 'force=true' as a query parameter." + } + ) + + @Override + public Result<Void> addPermToRole(final AuthzTrans trans, REQUEST rreq) { + // Translate Request into Perm and Role Objects + final Result<PermDAO.Data> rpd = mapper.permFromRPRequest(trans, rreq); + if(rpd.notOKorIsEmpty()) { + return Result.err(rpd); + } + final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq); + if(rrd.notOKorIsEmpty()) { + return Result.err(rrd); + } + + // Validate Role and Perm values + final ServiceValidator v = new ServiceValidator(); + if(v.perm(rpd.value) + .role(rrd.value) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.read(trans, rrd.value.ns, rrd.value.name); + if(rlrd.notOKorIsEmpty()) { + return Result.err(Status.ERR_RoleNotFound, "Role [%s] does not exist", rrd.value.fullName()); + } + + // Check Status of Data in DB (does it exist) + Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, rpd.value.ns, + rpd.value.type, rpd.value.instance, rpd.value.action); + PermDAO.Data createPerm = null; // if not null, create first + if(rlpd.notOKorIsEmpty()) { // Permission doesn't exist + if(trans.requested(force)) { + // Remove roles from perm data object so we just create the perm here + createPerm = rpd.value; + createPerm.roles.clear(); + } else { + return Result.err(Status.ERR_PermissionNotFound,"Permission [%s.%s|%s|%s] does not exist", + rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action); + } + } else { + if (rlpd.value.get(0).roles(false).contains(rrd.value.encode())) { + return Result.err(Status.ERR_ConflictAlreadyExists, + "Permission [%s.%s|%s|%s] already granted to Role [%s.%s]", + rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action, + rrd.value.ns,rrd.value.name + ); + } + } + + + Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, rpd.value,true, // Allow grants to create Approvals + new Mapper.Memo() { + @Override + public String get() { + return "Grant Permission [" + rpd.value.fullPerm() + ']' + + " to Role [" + rrd.value.fullName() + "]"; + } + }, + new MayChange() { + private Result<NsDAO.Data> nsd; + @Override + public Result<?> mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), rpd.value, Access.write); + } + return nsd; + } + }); + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rpd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans,fd.value, + rpd.value.fullPerm(), + trans.user(), + nsr.value.get(0), + FUTURE_OP.G); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", + rpd.value.ns, + rpd.value.type, + rpd.value.instance, + rpd.value.action); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + Result<Void> rv = null; + if(createPerm!=null) {// has been validated for creating + rv = func.createPerm(trans, createPerm, false); + } + if(rv==null || rv.isOK()) { + rv = func.addPermToRole(trans, rrd.value, rpd.value, false); + } + return rv; + default: + return Result.err(fd); + } + + } + + /** + * Delete Perms from Roles (UnGrant) + * @param trans + * @param roleFullName + * @return + */ + @ApiDoc( + method = DELETE, + path = "/authz/role/:role/perm", + params = {"role|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "Ungrant a permission from Role :role" } + ) + + @Override + public Result<Void> delPermFromRole(final AuthzTrans trans, REQUEST rreq) { + final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq); + if(updt.notOKorIsEmpty()) { + return Result.err(updt); + } + final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq); + if(rrd.notOKorIsEmpty()) { + return Result.err(rrd); + } + + final ServiceValidator v = new ServiceValidator(); + if(v.nullOrBlank(updt.value) + .nullOrBlank(rrd.value) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + return delPermFromRole(trans, updt.value,rrd.value, rreq); + } + + private Result<Void> delPermFromRole(final AuthzTrans trans, PermDAO.Data pdd, RoleDAO.Data rdd, REQUEST rreq) { + Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, pdd.ns, pdd.type, + pdd.instance, pdd.action); + + if(rlpd.notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, + "Permission [%s.%s|%s|%s] does not exist", + pdd.ns,pdd.type,pdd.instance,pdd.action); + } + + Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, pdd,true, // allow ungrants requests + new Mapper.Memo() { + @Override + public String get() { + return "Ungrant Permission [" + pdd.fullPerm() + ']' + + " from Role [" + rdd.fullName() + "]"; + } + }, + new MayChange() { + private Result<NsDAO.Data> nsd; + @Override + public Result<?> mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), pdd, Access.write); + } + return nsd; + } + }); + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pdd.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans,fd.value, + pdd.fullPerm(), + trans.user(), + nsr.value.get(0), + FUTURE_OP.UG + ); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", + pdd.ns, + pdd.type, + pdd.instance, + pdd.action); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.delPermFromRole(trans, rdd, pdd, false); + default: + return Result.err(fd); + } + } + +/* + @ApiDoc( + method = DELETE, + path = "/authz/role/:role/perm/:type/:instance/:action", + params = {"role|string|true", + "perm type|string|true", + "perm instance|string|true", + "perm action|string|true" + }, + expectedCode = 200, + errorCodes = {404,406}, + text = { "Ungrant a single permission from Role :role with direct key" } + ) +*/ + @Override + public Result<Void> delPermFromRole(AuthzTrans trans, String role, String type, String instance, String action) { + Result<Data> rpns = ques.deriveNs(trans, type); + if(rpns.notOKorIsEmpty()) { + return Result.err(rpns); + } + + final Validator v = new ServiceValidator(); + if(v.role(role) + .permType(rpns.value.name,rpns.value.parent) + .permInstance(instance) + .permAction(action) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<Data> rrns = ques.deriveNs(trans, role); + if(rrns.notOKorIsEmpty()) { + return Result.err(rrns); + } + + final Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, rrns.value.parent, rrns.value.name); + if(rrd.notOKorIsEmpty()) { + return Result.err(rrd); + } + + final Result<List<PermDAO.Data>> rpd = ques.permDAO.read(trans, rpns.value.parent, rpns.value.name, instance, action); + if(rpd.notOKorIsEmpty()) { + return Result.err(rpd); + } + + + return delPermFromRole(trans,rpd.value.get(0), rrd.value.get(0), mapper.ungrantRequest(trans, role, type, instance, action)); + } + + @ApiDoc( + method = DELETE, + path = "/authz/role/:role", + params = {"role|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "Delete the Role named :role"} + ) + + @Override + public Result<Void> deleteRole(AuthzTrans trans, String role) { + Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role); + if(rrdd.isOKhasData()) { + final ServiceValidator v = new ServiceValidator(); + if(v.nullOrBlank(rrdd.value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + return func.deleteRole(trans, rrdd.value, false, false); + } else { + return Result.err(rrdd); + } + } + + @ApiDoc( + method = DELETE, + path = "/authz/role", + params = {}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "Delete the Role referenced by RoleKey", + "You cannot normally delete a role which still has permissions granted or users assigned to it,", + "however the \"force\" property allows you to do just that. To do this: Add 'force=true'", + "as a query parameter.", + "<p>WARNING: Using force will remove all users and permission from this role. Use with care.</p>"} + ) + + @Override + public Result<Void> deleteRole(final AuthzTrans trans, REQUEST from) { + final Result<RoleDAO.Data> rd = mapper.role(trans, from); + final ServiceValidator v = new ServiceValidator(); + if(rd==null) { + return Result.err(Status.ERR_BadData,"Request does not contain Role"); + } + if(v.nullOrBlank(rd.value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final RoleDAO.Data role = rd.value; + if(ques.roleDAO.read(trans, role).notOKorIsEmpty() && !trans.requested(force)) { + return Result.err(Status.ERR_RoleNotFound, "Role [" + role.fullName() + "] does not exist"); + } + + Result<FutureDAO.Data> fd = mapper.future(trans,RoleDAO.TABLE,from,role,false, + new Mapper.Memo() { + @Override + public String get() { + return "Delete Role [" + role.fullName() + ']' + + " and all attached user roles"; + } + }, + new MayChange() { + private Result<NsDAO.Data> nsd; + @Override + public Result<?> mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), role, Access.write); + } + return nsd; + } + }); + + switch(fd.status) { + case OK: + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Result<String> rfc = func.createFuture(trans, fd.value, + role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Role Deletion [%s.%s] is saved for future processing", + rd.value.ns, + rd.value.name); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.deleteRole(trans,role,trans.requested(force), true /*preapproved*/); + default: + return Result.err(fd); + } + + } + +/*********************************** + * CRED + ***********************************/ + private class MayCreateCred implements MayChange { + private Result<NsDAO.Data> nsd; + private AuthzTrans trans; + private CredDAO.Data cred; + private Executor exec; + + public MayCreateCred(AuthzTrans trans, CredDAO.Data cred, Executor exec) { + this.trans = trans; + this.cred = cred; + this.exec = exec; + } + + @Override + public Result<?> mayChange() { + if(nsd==null) { + nsd = ques.validNSOfDomain(trans, cred.id); + } + // is Ns of CredID valid? + if(nsd.isOK()) { + try { + // Check Org Policy + if(trans.org().validate(trans,Policy.CREATE_MECHID, exec, cred.id)==null) { + return Result.ok(); + } else { + Result<?> rmc = ques.mayUser(trans, trans.user(), nsd.value, Access.write); + if(rmc.isOKhasData()) { + return rmc; + } + } + } catch (Exception e) { + trans.warn().log(e); + } + } else { + trans.warn().log(nsd.errorString()); + } + return Result.err(Status.ERR_Denied,"%s is not allowed to create %s in %s",trans.user(),cred.id,cred.ns); + } + } + + private class MayChangeCred implements MayChange { + + private Result<NsDAO.Data> nsd; + private AuthzTrans trans; + private CredDAO.Data cred; + public MayChangeCred(AuthzTrans trans, CredDAO.Data cred) { + this.trans = trans; + this.cred = cred; + } + + @Override + public Result<?> mayChange() { + // User can change himself (but not create) + if(trans.user().equals(cred.id)) { + return Result.ok(); + } + if(nsd==null) { + nsd = ques.validNSOfDomain(trans, cred.id); + } + // Get the Namespace + if(nsd.isOK()) { + if(ques.mayUser(trans, trans.user(), nsd.value,Access.write).isOK()) { + return Result.ok(); + } + String user[] = Split.split('.',trans.user()); + if(user.length>2) { + String company = user[user.length-1] + '.' + user[user.length-2]; + if(ques.isGranted(trans, trans.user(), ROOT_NS,"password",company,"reset")) { + return Result.ok(); + } + } + } + return Result.err(Status.ERR_Denied,"%s is not allowed to change %s in %s",trans.user(),cred.id,cred.ns); + } + + } + + private final long DAY_IN_MILLIS = 24*3600*1000; + + @ApiDoc( + method = POST, + path = "/authn/cred", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { "A credential consists of:", + "<ul><li>id - the ID to create within AAF. The domain is in reverse", + "order of Namespace (i.e. Users of Namespace com.att.myapp would be", + "AB1234@myapp.att.com</li>", + "<li>password - Company Policy Compliant Password</li></ul>", + "Note: AAF does support multiple credentials with the same ID.", + "Check with your organization if you have this implemented." + } + ) + @Override + public Result<Void> createUserCred(final AuthzTrans trans, REQUEST from) { + final String cmdDescription = ("Create User Credential"); + TimeTaken tt = trans.start(cmdDescription, Env.SUB); + + try { + Result<CredDAO.Data> rcred = mapper.cred(trans, from, true); + if(rcred.isOKhasData()) { + byte[] rawCred = rcred.value.cred.array(); + rcred = ques.userCredSetup(trans, rcred.value); + + final ServiceValidator v = new ServiceValidator(); + + if(v.cred(trans, trans.org(),rcred,true).err()) { // Note: Creates have stricter Validations + return Result.err(Status.ERR_BadData,v.errs()); + } + + + // 2016-4 Jonathan, New Behavior - If MechID is not registered with Org, deny creation + Identity mechID = null; + Organization org = trans.org(); + try { + mechID = org.getIdentity(trans, rcred.value.id); + } catch (Exception e1) { + trans.error().log(e1,rcred.value.id,"cannot be validated at this time"); + } + if(mechID==null || !mechID.isFound()) { + return Result.err(Status.ERR_Policy,"MechIDs must be registered with %s before provisioning in AAF",org.getName()); + } + + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(Status.ERR_NsNotFound,"Cannot provision %s on non-existent Namespace %s",mechID.id(),rcred.value.ns); + } + + + boolean firstID = false; + MayChange mc; + + CassExecutor exec = new CassExecutor(trans, func); + Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id); + if (rlcd.isOKhasData()) { + if (!org.canHaveMultipleCreds(rcred.value.id)) { + return Result.err(Status.ERR_ConflictAlreadyExists, "Credential exists"); + } + Result<Boolean> rb; + for (CredDAO.Data curr : rlcd.value) { + // May not use the same password in the list + // Note: ASPR specifies character differences, but we don't actually store the + // password to validate char differences. + + rb = ques.userCredCheck(trans, curr, rawCred); + if(rb.notOK()) { + return Result.err(rb); + } else if(rb.value){ + return Result.err(Status.ERR_Policy, "Credential content cannot be reused."); + } else if (Chrono.dateOnlyStamp(curr.expires).equals(Chrono.dateOnlyStamp(rcred.value.expires)) && curr.type==rcred.value.type) { + return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists, use 'reset'"); + } + } + } else { + try { + // 2016-04-12 Jonathan If Caller is the Sponsor and is also an Owner of NS, allow without special Perm + String theMechID = rcred.value.id; + Boolean otherMechIDs = false; + // find out if this is the only mechID. other MechIDs mean special handling (not automated) + for(CredDAO.Data cd : ques.credDAO.readNS(trans,nsr.value.get(0).name).value) { + if(!cd.id.equals(theMechID)) { + otherMechIDs = true; + break; + } + } + String reason; + // We can say "ID does not exist" here + if((reason=org.validate(trans, Policy.CREATE_MECHID, exec, theMechID,trans.user(),otherMechIDs.toString()))!=null) { + return Result.err(Status.ERR_Denied, reason); + } + firstID=true; + } catch (Exception e) { + return Result.err(e); + } + } + + mc = new MayCreateCred(trans, rcred.value, exec); + + final CredDAO.Data cdd = rcred.value; + Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false, // may want to enable in future. + new Mapper.Memo() { + @Override + public String get() { + return cmdDescription + " [" + + cdd.id + '|' + + cdd.type + '|' + + cdd.expires + ']'; + } + }, + mc); + + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans, fd.value, + rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires, + trans.user(), nsr.value.get(0), FUTURE_OP.C); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s] is saved for future processing", + rcred.value.id, + Integer.toString(rcred.value.type), + rcred.value.expires.toString()); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + try { + if(firstID) { + // && !nsr.value.get(0).isAdmin(trans.getUserPrincipal().getName())) { + Result<List<String>> admins = func.getAdmins(trans, nsr.value.get(0).name, false); + // OK, it's a first ID, and not by NS Admin, so let's set TempPassword length + // Note, we only do this on First time, because of possibility of + // prematurely expiring a production id + if(admins.isOKhasData() && !admins.value.contains(trans.user())) { + rcred.value.expires = org.expiration(null, Expiration.TempPassword).getTime(); + } + } + } catch (Exception e) { + trans.error().log(e, "While setting expiration to TempPassword"); + } + Result<?>udr = ques.credDAO.create(trans, rcred.value); + if(udr.isOK()) { + return Result.ok(); + } + return Result.err(udr); + default: + return Result.err(fd); + } + + } else { + return Result.err(rcred); + } + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authn/creds/ns/:ns", + params = {"ns|string|true"}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Return all IDs in Namespace :ns" + } + ) + @Override + public Result<USERS> getCredsByNS(AuthzTrans trans, String ns) { + final Validator v = new ServiceValidator(); + if(v.ns(ns).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // check if user is allowed to view NS + Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns); + if(rnd.notOK()) { + return Result.err(rnd); + } + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + TimeTaken tt = trans.start("MAP Creds by NS to Creds", Env.SUB); + try { + USERS users = mapper.newInstance(API.USERS); + Result<List<CredDAO.Data>> rlcd = ques.credDAO.readNS(trans, ns); + + if(rlcd.isOK()) { + if(!rlcd.isEmpty()) { + return mapper.cred(rlcd.value, users); + } + return Result.ok(users); + } else { + return Result.err(rlcd); + } + } finally { + tt.done(); + } + + } + + @ApiDoc( + method = GET, + path = "/authn/creds/id/:ns", + params = {"id|string|true"}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Return all IDs in for ID" + ,"(because IDs are multiple, due to multiple Expiration Dates)" + } + ) + @Override + public Result<USERS> getCredsByID(AuthzTrans trans, String id) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("ID",id).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + String ns = Question.domain2ns(id); + // check if user is allowed to view NS + Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns); + if(rnd.notOK()) { + return Result.err(rnd); + } + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + TimeTaken tt = trans.start("MAP Creds by ID to Creds", Env.SUB); + try { + USERS users = mapper.newInstance(API.USERS); + Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, id); + + if(rlcd.isOK()) { + if(!rlcd.isEmpty()) { + return mapper.cred(rlcd.value, users); + } + return Result.ok(users); + } else { + return Result.err(rlcd); + } + } finally { + tt.done(); + } + + } + + @ApiDoc( + method = GET, + path = "/authn/certs/id/:id", + params = {"id|string|true"}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Return Cert Info for ID" + } + ) + @Override + public Result<CERTS> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id) { + TimeTaken tt = trans.start("Get Cert Info by ID", Env.SUB); + try { + CERTS certs = mapper.newInstance(API.CERTS); + Result<List<CertDAO.Data>> rlcd = ques.certDAO.readID(trans, id); + + if(rlcd.isOK()) { + if(!rlcd.isEmpty()) { + return mapper.cert(rlcd.value, certs); + } + return Result.ok(certs); + } else { + return Result.err(rlcd); + } + } finally { + tt.done(); + } + + } + + @ApiDoc( + method = PUT, + path = "/authn/cred", + params = {}, + expectedCode = 200, + errorCodes = {300,403,404,406}, + text = { "Reset a Credential Password. If multiple credentials exist for this", + "ID, you will need to specify which entry you are resetting in the", + "CredRequest object" + } + ) + @Override + public Result<Void> changeUserCred(final AuthzTrans trans, REQUEST from) { + final String cmdDescription = "Update User Credential"; + TimeTaken tt = trans.start(cmdDescription, Env.SUB); + try { + Result<CredDAO.Data> rcred = mapper.cred(trans, from, true); + if(rcred.isOKhasData()) { + rcred = ques.userCredSetup(trans, rcred.value); + + final ServiceValidator v = new ServiceValidator(); + + if(v.cred(trans, trans.org(),rcred,false).err()) {// Note: Creates have stricter Validations + return Result.err(Status.ERR_BadData,v.errs()); + } + Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id); + if(rlcd.notOKorIsEmpty()) { + return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); + } + + MayChange mc = new MayChangeCred(trans, rcred.value); + Result<?> rmc = mc.mayChange(); + if (rmc.notOK()) { + return Result.err(rmc); + } + + Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value); + if(ri.notOK()) { + return Result.err(ri); + } + int entry = ri.value; + + + final CredDAO.Data cred = rcred.value; + + Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false, + new Mapper.Memo() { + @Override + public String get() { + return cmdDescription + " [" + + cred.id + '|' + + cred.type + '|' + + cred.expires + ']'; + } + }, + mc); + + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans, fd.value, + rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires, + trans.user(), nsr.value.get(0), FUTURE_OP.U); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s]", + rcred.value.id, + Integer.toString(rcred.value.type), + rcred.value.expires.toString()); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + Result<?>udr = null; + // If we are Resetting Password on behalf of someone else (am not the Admin) + // use TempPassword Expiration time. + Expiration exp; + if(ques.isAdmin(trans, trans.user(), nsr.value.get(0).name)) { + exp = Expiration.Password; + } else { + exp = Expiration.TempPassword; + } + + Organization org = trans.org(); + CredDAO.Data current = rlcd.value.get(entry); + // If user resets password in same day, we will have a primary key conflict, so subtract 1 day + if (current.expires.equals(rcred.value.expires) + && rlcd.value.get(entry).type==rcred.value.type) { + GregorianCalendar gc = org.expiration(null, exp,rcred.value.id); + gc = Chrono.firstMomentOfDay(gc); + gc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay()); + rcred.value.expires = new Date(gc.getTimeInMillis() - DAY_IN_MILLIS); + } else { + rcred.value.expires = org.expiration(null,exp).getTime(); + } + // Copy in other fields 10/21/2016 + rcred.value.notes=current.notes; + + udr = ques.credDAO.create(trans, rcred.value); + if(udr.isOK()) { + udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false); + } + if (udr.isOK()) { + return Result.ok(); + } + + return Result.err(udr); + default: + return Result.err(fd); + } + } else { + return Result.err(rcred); + } + } finally { + tt.done(); + } + } + + /* + * Codify the way to get Either Choice Needed or actual Integer from Credit Request + */ + private Result<Integer> selectEntryIfMultiple(final CredRequest cr, List<CredDAO.Data> lcd) { + int entry = 0; + if (lcd.size() > 1) { + String inputOption = cr.getEntry(); + if (inputOption == null) { + String message = selectCredFromList(lcd, false); + String[] variables = buildVariables(lcd); + return Result.err(Status.ERR_ChoiceNeeded, message, variables); + } else { + entry = Integer.parseInt(inputOption) - 1; + } + if (entry < 0 || entry >= lcd.size()) { + return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); + } + } + return Result.ok(entry); + } + + @ApiDoc( + method = PUT, + path = "/authn/cred/:days", + params = {"days|string|true"}, + expectedCode = 200, + errorCodes = {300,403,404,406}, + text = { "Extend a Credential Expiration Date. The intention of this API is", + "to avoid an outage in PROD due to a Credential expiring before it", + "can be configured correctly. Measures are being put in place ", + "so that this is not abused." + } + ) + @Override + public Result<Void> extendUserCred(final AuthzTrans trans, REQUEST from, String days) { + TimeTaken tt = trans.start("Extend User Credential", Env.SUB); + try { + Result<CredDAO.Data> cred = mapper.cred(trans, from, false); + Organization org = trans.org(); + final ServiceValidator v = new ServiceValidator(); + if(v.notOK(cred).err() || + v.nullOrBlank(cred.value.id, "Invalid ID").err() || + v.user(org,cred.value.id).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + try { + String reason; + if ((reason=org.validate(trans, Policy.MAY_EXTEND_CRED_EXPIRES, new CassExecutor(trans,func)))!=null) { + return Result.err(Status.ERR_Policy,reason); + } + } catch (Exception e) { + String msg; + trans.error().log(e, msg="Could not contact Organization for User Validation"); + return Result.err(Status.ERR_Denied, msg); + } + + // Get the list of Cred Entries + Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id); + if(rlcd.notOKorIsEmpty()) { + return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); + } + + //Need to do the "Pick Entry" mechanism + Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value); + if(ri.notOK()) { + return Result.err(ri); + } + + CredDAO.Data found = rlcd.value.get(ri.value); + CredDAO.Data cd = cred.value; + // Copy over the cred + cd.id = found.id; + cd.cred = found.cred; + cd.other = found.other; + cd.type = found.type; + cd.notes = found.notes; + cd.ns = found.ns; + cd.expires = org.expiration(null, Expiration.ExtendPassword,days).getTime(); + + cred = ques.credDAO.create(trans, cd); + if(cred.isOK()) { + return Result.ok(); + } + return Result.err(cred); + } finally { + tt.done(); + } + } + + private String[] buildVariables(List<CredDAO.Data> value) { + // ensure credentials are sorted so we can fully automate Cred regression test + Collections.sort(value, new Comparator<CredDAO.Data>() { + @Override + public int compare(CredDAO.Data cred1, CredDAO.Data cred2) { + return cred1.expires.compareTo(cred2.expires); + } + }); + String [] vars = new String[value.size()+1]; + vars[0]="Choice"; + for (int i = 0; i < value.size(); i++) { + vars[i+1] = value.get(i).id + " " + value.get(i).type + + " |" + value.get(i).expires; + } + return vars; + } + + private String selectCredFromList(List<CredDAO.Data> value, boolean isDelete) { + StringBuilder errMessage = new StringBuilder(); + String userPrompt = isDelete?"Select which cred to delete (set force=true to delete all):":"Select which cred to update:"; + int numSpaces = value.get(0).id.length() - "Id".length(); + + errMessage.append(userPrompt + '\n'); + errMessage.append(" Id"); + for (int i = 0; i < numSpaces; i++) { + errMessage.append(' '); + } + errMessage.append(" Type Expires" + '\n'); + for(int i=0;i<value.size();++i) { + errMessage.append(" %s\n"); + } + errMessage.append("Run same command again with chosen entry as last parameter"); + + return errMessage.toString(); + + } + + @ApiDoc( + method = DELETE, + path = "/authn/cred", + params = {}, + expectedCode = 200, + errorCodes = {300,403,404,406}, + text = { "Delete a Credential. If multiple credentials exist for this", + "ID, you will need to specify which entry you are deleting in the", + "CredRequest object." + } + ) + @Override + public Result<Void> deleteUserCred(AuthzTrans trans, REQUEST from) { + final Result<CredDAO.Data> cred = mapper.cred(trans, from, false); + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("cred", cred.value.id).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id); + if(rlcd.notOKorIsEmpty()) { + // Empty Creds should have no user_roles. + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + ques.userRoleDAO.delete(trans, data, false); + } + } + return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); + } + boolean isLastCred = rlcd.value.size()==1; + + MayChange mc = new MayChangeCred(trans,cred.value); + Result<?> rmc = mc.mayChange(); + if (rmc.notOK()) { + return Result.err(rmc); + } + + int entry = 0; + if(!trans.requested(force)) { + if (rlcd.value.size() > 1) { + CredRequest cr = (CredRequest)from; + String inputOption = cr.getEntry(); + if (inputOption == null) { + String message = selectCredFromList(rlcd.value, true); + String[] variables = buildVariables(rlcd.value); + return Result.err(Status.ERR_ChoiceNeeded, message, variables); + } else { + try { + if(inputOption.length()>5) { // should be a date + Date d = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(inputOption).toGregorianCalendar().getTime(); + entry = 0; + for(CredDAO.Data cd : rlcd.value) { + if(cd.type.equals(cr.getType()) && cd.expires.equals(d)) { + break; + } + ++entry; + } + } else { + entry = Integer.parseInt(inputOption) - 1; + } + } catch(NullPointerException e) { + return Result.err(Status.ERR_BadData, "Invalid Date Format for Entry"); + } catch(NumberFormatException e) { + return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); + } + } + isLastCred = (entry==-1)?true:false; + } else { + isLastCred = true; + } + if (entry < -1 || entry >= rlcd.value.size()) { + return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); + } + } + + Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from,cred.value,false, + new Mapper.Memo() { + @Override + public String get() { + return "Delete Credential [" + + cred.value.id + + ']'; + } + }, + mc); + + Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, cred.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans, fd.value, cred.value.id, + trans.user(), nsr.value.get(0), FUTURE_OP.D); + + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Credential Delete [%s] is saved for future processing",cred.value.id); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + Result<?>udr = null; + if (!trans.requested(force)) { + if(entry<0 || entry >= rlcd.value.size()) { + return Result.err(Status.ERR_BadData,"Invalid Choice [" + entry + "] chosen for Delete [%s] is saved for future processing",cred.value.id); + } + udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false); + } else { + for (CredDAO.Data curr : rlcd.value) { + udr = ques.credDAO.delete(trans, curr, false); + if (udr.notOK()) { + return Result.err(udr); + } + } + } + if(isLastCred) { + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + ques.userRoleDAO.delete(trans, data, false); + } + } + } + if (udr.isOK()) { + return Result.ok(); + } + return Result.err(udr); + default: + return Result.err(fd); + } + + } + + + @Override + public Result<Date> doesCredentialMatch(AuthzTrans trans, REQUEST credReq) { + TimeTaken tt = trans.start("Does Credential Match", Env.SUB); + try { + // Note: Mapper assigns RAW type + Result<CredDAO.Data> data = mapper.cred(trans, credReq,false); + if(data.notOKorIsEmpty()) { + return Result.err(data); + } + CredDAO.Data cred = data.value; // of the Mapped Cred + if(cred.cred==null) { + return Result.err(Result.ERR_BadData,"No Password"); + } else { + return ques.doesUserCredMatch(trans, cred.id, cred.cred.array()); + } + + } catch (DAOException e) { + trans.error().log(e,"Error looking up cred"); + return Result.err(Status.ERR_Denied,"Credential does not match"); + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authn/basicAuth", + params = {}, + expectedCode = 200, + errorCodes = { 403 }, + text = { "!!!! DEPRECATED without X509 Authentication STOP USING THIS API BY DECEMBER 2017, or use Certificates !!!!\n" + + "Use /authn/validate instead\n" + + "Note: Validate a Password using BasicAuth Base64 encoded Header. This HTTP/S call is intended as a fast" + + " User/Password lookup for Security Frameworks, and responds 200 if it passes BasicAuth " + + "security, and 403 if it does not." } + ) + private void basicAuth() { + // This is a place holder for Documentation. The real BasicAuth API does not call Service. + } + + @ApiDoc( + method = POST, + path = "/authn/validate", + params = {}, + expectedCode = 200, + errorCodes = { 403 }, + text = { "Validate a Credential given a Credential Structure. This is a more comprehensive validation, can " + + "do more than BasicAuth as Credential types exp" } + ) + @Override + public Result<Date> validateBasicAuth(AuthzTrans trans, String basicAuth) { + //TODO how to make sure people don't use this in browsers? Do we care? + TimeTaken tt = trans.start("Validate Basic Auth", Env.SUB); + try { + BasicPrincipal bp = new BasicPrincipal(basicAuth,trans.org().getRealm()); + Result<Date> rq = ques.doesUserCredMatch(trans, bp.getName(), bp.getCred()); + // Note: Only want to log problem, don't want to send back to end user + if(rq.isOK()) { + return rq; + } else { + trans.audit().log(rq.errorString()); + } + } catch (Exception e) { + trans.warn().log(e); + } finally { + tt.done(); + } + return Result.err(Status.ERR_Denied,"Bad Basic Auth"); + } + +/*********************************** + * USER-ROLE + ***********************************/ + @ApiDoc( + method = POST, + path = "/authz/userRole", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { "Create a UserRole relationship (add User to Role)", + "A UserRole is an object Representation of membership of a Role for limited time.", + "If a shorter amount of time for Role ownership is required, use the 'End' field.", + "** Note: Owners of Namespaces will be required to revalidate users in these roles ", + "before Expirations expire. Namespace owners will be notified by email." + } + ) + @Override + public Result<Void> createUserRole(final AuthzTrans trans, REQUEST from) { + TimeTaken tt = trans.start("Create UserRole", Env.SUB); + try { + Result<UserRoleDAO.Data> urr = mapper.userRole(trans, from); + if(urr.notOKorIsEmpty()) { + return Result.err(urr); + } + final UserRoleDAO.Data userRole = urr.value; + + final ServiceValidator v = new ServiceValidator(); + if(v.user_role(userRole).err() || + v.user(trans.org(), userRole.user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + + + // Check if user can change first + Result<FutureDAO.Data> fd = mapper.future(trans,UserRoleDAO.TABLE,from,urr.value,true, // may request Approvals + new Mapper.Memo() { + @Override + public String get() { + return "Add User [" + userRole.user + "] to Role [" + + userRole.role + + ']'; + } + }, + new MayChange() { + private Result<NsDAO.Data> nsd; + @Override + public Result<?> mayChange() { + if(nsd==null) { + RoleDAO.Data r = RoleDAO.Data.decode(userRole); + nsd = ques.mayUser(trans, trans.user(), r, Access.write); + } + return nsd; + } + }); + Result<NsDAO.Data> nsr = ques.deriveNs(trans, userRole.role); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans, fd.value, userRole.user+'|'+userRole.ns + '.' + userRole.rname, + userRole.user, nsr.value, FUTURE_OP.C); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "UserRole [%s - %s.%s] is saved for future processing", + userRole.user, + userRole.ns, + userRole.rname); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.addUserRole(trans, userRole); + default: + return Result.err(fd); + } + } finally { + tt.done(); + } + } + + /** + * getUserRolesByRole + */ + @ApiDoc( + method = GET, + path = "/authz/userRoles/role/:role", + params = {"role|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "List all Users that are attached to Role specified in :role", + } + ) + @Override + public Result<USERROLES> getUserRolesByRole(AuthzTrans trans, String role) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Role",role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<RoleDAO.Data> rrdd; + rrdd = RoleDAO.Data.decode(trans,ques,role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + // May Requester see result? + Result<NsDAO.Data> ns = ques.mayUser(trans,trans.user(), rrdd.value,Access.read); + if (ns.notOK()) { + return Result.err(ns); + } + + // boolean filter = true; + // if (ns.value.isAdmin(trans.user()) || ns.value.isResponsible(trans.user())) + // filter = false; + + // Get list of roles per user, then add to Roles as we go + HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>(); + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + userSet.add(data); + } + } + + @SuppressWarnings("unchecked") + USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES); + // Checked for permission + mapper.userRoles(trans, userSet, users); + return Result.ok(users); + } + /** + * getUserRolesByRole + */ + @ApiDoc( + method = GET, + path = "/authz/userRoles/user/:user", + params = {"role|string|true"}, + expectedCode = 200, + errorCodes = {404,406}, + text = { "List all UserRoles for :user", + } + ) + @Override + public Result<USERROLES> getUserRolesByUser(AuthzTrans trans, String user) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User",user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Get list of roles per user, then add to Roles as we go + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user); + if(rlurd.notOK()) { + return Result.err(rlurd); + } + + /* Check for + * 1) is User + * 2) is User's Supervisor + * 3) Has special global access =read permission + * + * If none of the 3, then filter results to NSs in which Calling User has Ns.access * read + */ + boolean mustFilter; + String callingUser = trans.getUserPrincipal().getName(); + NsDAO.Data ndd = new NsDAO.Data(); + + if(user.equals(callingUser)) { + mustFilter = false; + } else { + Organization org = trans.org(); + try { + Identity orgID = org.getIdentity(trans, user); + Identity manager = orgID==null?null:orgID.responsibleTo(); + if(orgID!=null && (manager!=null && callingUser.equals(manager.fullID()))) { + mustFilter = false; + } else if(ques.isGranted(trans, callingUser, ROOT_NS, Question.ACCESS, "*", Access.read.name())) { + mustFilter=false; + } else { + mustFilter = true; + } + } catch (OrganizationException e) { + trans.env().log(e); + mustFilter = true; + } + } + + List<UserRoleDAO.Data> content; + if(mustFilter) { + content = new ArrayList<UserRoleDAO.Data>(rlurd.value.size()); // avoid multi-memory redos + + for(UserRoleDAO.Data data : rlurd.value) { + ndd.name=data.ns; + Result<Data> mur = ques.mayUser(trans, callingUser, ndd, Access.read); + if(mur.isOK()){ + content.add(data); + } + } + + } else { + content = rlurd.value; + } + + + @SuppressWarnings("unchecked") + USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES); + // Checked for permission + mapper.userRoles(trans, content, users); + return Result.ok(users); + } + + + @ApiDoc( + method = PUT, + path = "/authz/userRole/user", + params = {}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Set a User's roles to the roles specified in the UserRoleRequest object.", + "WARNING: Roles supplied will be the ONLY roles attached to this user", + "If no roles are supplied, user's roles are reset." + } + ) + @Override + public Result<Void> resetRolesForUser(AuthzTrans trans, REQUEST rreq) { + Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq); + final ServiceValidator v = new ServiceValidator(); + if(rurdd.notOKorIsEmpty()) { + return Result.err(rurdd); + } + if (v.user(trans.org(), rurdd.value.user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Set<String> currRoles = new HashSet<String>(); + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, rurdd.value.user); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + currRoles.add(data.role); + } + } + + Result<Void> rv = null; + String[] roles; + if(rurdd.value.role==null) { + roles = new String[0]; + } else { + roles = rurdd.value.role.split(","); + } + + for (String role : roles) { + if (v.role(role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + rurdd.value.role(rrdd.value); + + Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), rrdd.value,Access.write); + if (nsd.notOK()) { + return Result.err(nsd); + } + Result<NsDAO.Data> nsr = ques.deriveNs(trans, role); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + if(currRoles.contains(role)) { + currRoles.remove(role); + } else { + rv = func.addUserRole(trans, rurdd.value); + if (rv.notOK()) { + return rv; + } + } + } + + for (String role : currRoles) { + rurdd.value.role(trans,ques,role); + rv = ques.userRoleDAO.delete(trans, rurdd.value, false); + if(rv.notOK()) { + trans.info().log(rurdd.value.user,"/",rurdd.value.role, "expected to be deleted, but does not exist"); + // return rv; // if it doesn't exist, don't error out + } + + } + + return Result.ok(); + + } + + @ApiDoc( + method = PUT, + path = "/authz/userRole/role", + params = {}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Set a Role's users to the users specified in the UserRoleRequest object.", + "WARNING: Users supplied will be the ONLY users attached to this role", + "If no users are supplied, role's users are reset." + } + ) + @Override + public Result<Void> resetUsersForRole(AuthzTrans trans, REQUEST rreq) { + Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq); + if(rurdd.notOKorIsEmpty()) { + return Result.err(rurdd); + } + final ServiceValidator v = new ServiceValidator(); + if (v.user_role(rurdd.value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + RoleDAO.Data rd = RoleDAO.Data.decode(rurdd.value); + + Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), rd, Access.write); + if (nsd.notOK()) { + return Result.err(nsd); + } + + Result<NsDAO.Data> nsr = ques.deriveNs(trans, rurdd.value.role); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Set<String> currUsers = new HashSet<String>(); + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, rurdd.value.role); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + currUsers.add(data.user); + } + } + + // found when connected remotely to DEVL, can't replicate locally + // inconsistent errors with cmd: role user setTo [nothing] + // deleteUserRole --> read --> get --> cacheIdx(?) + // sometimes returns idx for last added user instead of user passed in + // cache bug? + + + Result<Void> rv = null; + String[] users = {}; + if (rurdd.value.user != null) { + users = rurdd.value.user.split(","); + } + + for (String user : users) { + if (v.user(trans.org(), user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + rurdd.value.user = user; + + if(currUsers.contains(user)) { + currUsers.remove(user); + } else { + rv = func.addUserRole(trans, rurdd.value); + if (rv.notOK()) { + return rv; + } + } + } + + for (String user : currUsers) { + rurdd.value.user = user; + rv = ques.userRoleDAO.delete(trans, rurdd.value, false); + if(rv.notOK()) { + trans.info().log(rurdd.value, "expected to be deleted, but not exists"); + return rv; + } + } + + return Result.ok(); + } + + @ApiDoc( + method = GET, + path = "/authz/userRole/extend/:user/:role", + params = { "user|string|true", + "role|string|true" + }, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Extend the Expiration of this User Role by the amount set by Organization", + "Requestor must be allowed to modify the role" + } + ) + @Override + public Result<Void> extendUserRole(AuthzTrans trans, String user, String role) { + Organization org = trans.org(); + final ServiceValidator v = new ServiceValidator(); + if(v.user(org, user) + .role(role) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + Result<NsDAO.Data> rcr = ques.mayUser(trans, trans.user(), rrdd.value, Access.write); + boolean mayNotChange; + if((mayNotChange = rcr.notOK()) && !trans.requested(future)) { + return Result.err(rcr); + } + + Result<List<UserRoleDAO.Data>> rr = ques.userRoleDAO.read(trans, user,role); + if(rr.notOK()) { + return Result.err(rr); + } + for(UserRoleDAO.Data userRole : rr.value) { + if(mayNotChange) { // Function exited earlier if !trans.futureRequested + FutureDAO.Data fto = new FutureDAO.Data(); + fto.target=UserRoleDAO.TABLE; + fto.memo = "Extend User ["+userRole.user+"] in Role ["+userRole.role+"]"; + GregorianCalendar now = new GregorianCalendar(); + fto.start = now.getTime(); + fto.expires = org.expiration(now, Expiration.Future).getTime(); + try { + fto.construct = userRole.bytify(); + } catch (IOException e) { + trans.error().log(e, "Error while bytifying UserRole for Future"); + return Result.err(e); + } + + Result<String> rfc = func.createFuture(trans, fto, + userRole.user+'|'+userRole.role, userRole.user, rcr.value, FUTURE_OP.U); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing", + userRole.user, + userRole.role); + } else { + return Result.err(rfc); + } + } else { + return func.extendUserRole(trans, userRole, false); + } + } + return Result.err(Result.ERR_NotFound,"This user and role doesn't exist"); + } + + @ApiDoc( + method = DELETE, + path = "/authz/userRole/:user/:role", + params = { "user|string|true", + "role|string|true" + }, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Remove Role :role from User :user." + } + ) + @Override + public Result<Void> deleteUserRole(AuthzTrans trans, String usr, String role) { + Validator val = new ServiceValidator(); + if(val.nullOrBlank("User", usr) + .nullOrBlank("Role", role).err()) { + return Result.err(Status.ERR_BadData, val.errs()); + } + + boolean mayNotChange; + Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + RoleDAO.Data rdd = rrdd.value; + Result<NsDAO.Data> rns = ques.mayUser(trans, trans.user(), rdd, Access.write); + + // Make sure we don't delete the last owner of valid NS + if(rns.isOKhasData() && Question.OWNER.equals(rdd.name) && ques.countOwner(trans,rdd.ns)<=1) { + return Result.err(Status.ERR_Denied,"You may not delete the last Owner of " + rdd.ns ); + } + + if(mayNotChange=rns.notOK()) { + if(!trans.requested(future)) { + return Result.err(rns); + } + } + + Result<List<UserRoleDAO.Data>> rulr; + if((rulr=ques.userRoleDAO.read(trans, usr, role)).notOKorIsEmpty()) { + return Result.err(Status.ERR_UserRoleNotFound, "User [ "+usr+" ] is not " + + "Assigned to the Role [ " + role + " ]"); + } + + UserRoleDAO.Data userRole = rulr.value.get(0); + if(mayNotChange) { // Function exited earlier if !trans.futureRequested + FutureDAO.Data fto = new FutureDAO.Data(); + fto.target=UserRoleDAO.TABLE; + fto.memo = "Remove User ["+userRole.user+"] from Role ["+userRole.role+"]"; + GregorianCalendar now = new GregorianCalendar(); + fto.start = now.getTime(); + fto.expires = trans.org().expiration(now, Expiration.Future).getTime(); + + Result<String> rfc = func.createFuture(trans, fto, + userRole.user+'|'+userRole.role, userRole.user, rns.value, FUTURE_OP.D); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing", + userRole.user, + userRole.role); + } else { + return Result.err(rfc); + } + } else { + return ques.userRoleDAO.delete(trans, rulr.value.get(0), false); + } + } + + @ApiDoc( + method = GET, + path = "/authz/userRole/:user/:role", + params = {"user|string|true", + "role|string|true"}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Returns the User (with Expiration date from listed User/Role) if it exists" + } + ) + @Override + public Result<USERS> getUserInRole(AuthzTrans trans, String user, String role) { + final Validator v = new ServiceValidator(); + if(v.role(role).nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + +// Result<NsDAO.Data> ns = ques.deriveNs(trans, role); +// if (ns.notOK()) return Result.err(ns); +// +// Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write); + // May calling user see by virtue of the Role + Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>(); + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readUserInRole(trans, user, role); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + userSet.add(data); + } + } + + @SuppressWarnings("unchecked") + USERS users = (USERS) mapper.newInstance(API.USERS); + mapper.users(trans, userSet, users); + return Result.ok(users); + } + + @ApiDoc( + method = GET, + path = "/authz/users/role/:role", + params = {"user|string|true", + "role|string|true"}, + expectedCode = 200, + errorCodes = {403,404,406}, + text = { "Returns the User (with Expiration date from listed User/Role) if it exists" + } + ) + @Override + public Result<USERS> getUsersByRole(AuthzTrans trans, String role) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Role",role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + +// Result<NsDAO.Data> ns = ques.deriveNs(trans, role); +// if (ns.notOK()) return Result.err(ns); +// +// Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write); + // May calling user see by virtue of the Role + Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + boolean contactOnly = false; + // Allow the request of any valid user to find the contact of the NS (Owner) + Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read); + if(rnd.notOK()) { + if(Question.OWNER.equals(rrdd.value.name)) { + contactOnly = true; + } else { + return Result.err(rnd); + } + } + + HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>(); + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role); + if(rlurd.isOK()) { + for(UserRoleDAO.Data data : rlurd.value) { + if(contactOnly) { //scrub data + // Can't change actual object, or will mess up the cache. + UserRoleDAO.Data scrub = new UserRoleDAO.Data(); + scrub.ns = data.ns; + scrub.rname = data.rname; + scrub.role = data.role; + scrub.user = data.user; + userSet.add(scrub); + } else { + userSet.add(data); + } + } + } + + @SuppressWarnings("unchecked") + USERS users = (USERS) mapper.newInstance(API.USERS); + mapper.users(trans, userSet, users); + return Result.ok(users); + } + + /** + * getUsersByPermission + */ + @ApiDoc( + method = GET, + path = "/authz/users/perm/:type/:instance/:action", + params = { "type|string|true", + "instance|string|true", + "action|string|true" + }, + expectedCode = 200, + errorCodes = {404,406}, + text = { "List all Users that have Permission specified by :type :instance :action", + } + ) + @Override + public Result<USERS> getUsersByPermission(AuthzTrans trans, String type, String instance, String action) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Type",type) + .nullOrBlank("Instance",instance) + .nullOrBlank("Action",action) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<NsSplit> nss = ques.deriveNsSplit(trans, type); + if(nss.notOK()) { + return Result.err(nss); + } + + Result<List<NsDAO.Data>> nsd = ques.nsDAO.read(trans, nss.value.ns); + if (nsd.notOK()) { + return Result.err(nsd); + } + + boolean allInstance = ASTERIX.equals(instance); + boolean allAction = ASTERIX.equals(action); + // Get list of roles per Permission, + // Then loop through Roles to get Users + // Note: Use Sets to avoid processing or responding with Duplicates + Set<String> roleUsed = new HashSet<String>(); + Set<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>(); + + if(!nss.isEmpty()) { + Result<List<PermDAO.Data>> rlp = ques.permDAO.readByType(trans, nss.value.ns, nss.value.name); + if(rlp.isOKhasData()) { + for(PermDAO.Data pd : rlp.value) { + if((allInstance || pd.instance.equals(instance)) && + (allAction || pd.action.equals(action))) { + if(ques.mayUser(trans, trans.user(),pd,Access.read).isOK()) { + for(String role : pd.roles) { + if(!roleUsed.contains(role)) { // avoid evaluating Role many times + roleUsed.add(role); + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role.replace('|', '.')); + if(rlurd.isOKhasData()) { + for(UserRoleDAO.Data urd : rlurd.value) { + userSet.add(urd); + } + } + } + } + } + } + } + } + } + @SuppressWarnings("unchecked") + USERS users = (USERS) mapper.newInstance(API.USERS); + mapper.users(trans, userSet, users); + return Result.ok(users); + } + + /*********************************** + * HISTORY + ***********************************/ + @Override + public Result<HISTORY> getHistoryByUser(final AuthzTrans trans, String user, final int[] yyyymm, final int sort) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User",user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<NsDAO.Data> rnd; + // Users may look at their own data + if(trans.user().equals(user)) { + // Users may look at their own data + } else { + int at = user.indexOf('@'); + if(at>=0 && trans.org().getRealm().equals(user.substring(at+1))) { + NsDAO.Data nsd = new NsDAO.Data(); + nsd.name = Question.domain2ns(user); + rnd = ques.mayUser(trans, trans.user(), nsd, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + } else { + rnd = ques.validNSOfDomain(trans, user); + if(rnd.notOK()) { + return Result.err(rnd); + } + + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + } + } + Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readByUser(trans, user, yyyymm); + if(resp.notOK()) { + return Result.err(resp); + } + return mapper.history(trans, resp.value,sort); + } + + @Override + public Result<HISTORY> getHistoryByRole(AuthzTrans trans, String role, int[] yyyymm, final int sort) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Role",role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, role, "role", yyyymm); + if(resp.notOK()) { + return Result.err(resp); + } + return mapper.history(trans, resp.value,sort); + } + + @Override + public Result<HISTORY> getHistoryByPerm(AuthzTrans trans, String type, int[] yyyymm, final int sort) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Type",type) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // May user see Namespace of Permission (since it's only one piece... we can't check for "is permission part of") + Result<NsDAO.Data> rnd = ques.deriveNs(trans,type); + if(rnd.notOK()) { + return Result.err(rnd); + } + + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, type, "perm", yyyymm); + if(resp.notOK()) { + return Result.err(resp); + } + return mapper.history(trans, resp.value,sort); + } + + @Override + public Result<HISTORY> getHistoryByNS(AuthzTrans trans, String ns, int[] yyyymm, final int sort) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("NS",ns) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns); + if(rnd.notOK()) { + return Result.err(rnd); + } + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, ns, "ns", yyyymm); + if(resp.notOK()) { + return Result.err(resp); + } + return mapper.history(trans, resp.value,sort); + } + +/*********************************** + * DELEGATE + ***********************************/ + @Override + public Result<Void> createDelegate(final AuthzTrans trans, REQUEST base) { + return createOrUpdateDelegate(trans, base, Question.Access.create); + } + + @Override + public Result<Void> updateDelegate(AuthzTrans trans, REQUEST base) { + return createOrUpdateDelegate(trans, base, Question.Access.write); + } + + + private Result<Void> createOrUpdateDelegate(final AuthzTrans trans, REQUEST base, final Access access) { + final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base); + final ServiceValidator v = new ServiceValidator(); + if(v.delegate(trans.org(),rd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + final DelegateDAO.Data dd = rd.value; + + Result<List<DelegateDAO.Data>> ddr = ques.delegateDAO.read(trans, dd); + if(access==Access.create && ddr.isOKhasData()) { + return Result.err(Status.ERR_ConflictAlreadyExists, "[%s] already delegates to [%s]", dd.user, ddr.value.get(0).delegate); + } else if(access!=Access.create && ddr.notOKorIsEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] does not have a Delegate Record to [%s].",dd.user,access.name()); + } + Result<Void> rv = ques.mayUser(trans, dd, access); + if(rv.notOK()) { + return rv; + } + + Result<FutureDAO.Data> fd = mapper.future(trans,DelegateDAO.TABLE,base, dd, false, + new Mapper.Memo() { + @Override + public String get() { + StringBuilder sb = new StringBuilder(); + sb.append(access.name()); + sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); + sb.append("Delegate "); + sb.append(access==Access.create?"[":"to ["); + sb.append(rd.value.delegate); + sb.append("] for ["); + sb.append(rd.value.user); + sb.append(']'); + return sb.toString(); + } + }, + new MayChange() { + @Override + public Result<?> mayChange() { + return Result.ok(); // Validate in code above + } + }); + + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans, fd.value, + dd.user, trans.user(),null, access==Access.create?FUTURE_OP.C:FUTURE_OP.U); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Delegate for [%s]", + dd.user); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + if(access==Access.create) { + Result<DelegateDAO.Data> rdr = ques.delegateDAO.create(trans, dd); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + } else { + return ques.delegateDAO.update(trans, dd); + } + default: + return Result.err(fd); + } + } + + @Override + public Result<Void> deleteDelegate(AuthzTrans trans, REQUEST base) { + final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base); + final Validator v = new ServiceValidator(); + if(v.notOK(rd).nullOrBlank("User", rd.value.user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<List<DelegateDAO.Data>> ddl; + if((ddl=ques.delegateDAO.read(trans, rd.value)).notOKorIsEmpty()) { + return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate"); + } + final DelegateDAO.Data dd = ddl.value.get(0); + Result<Void> rv = ques.mayUser(trans, dd, Access.write); + if(rv.notOK()) { + return rv; + } + + return ques.delegateDAO.delete(trans, dd, false); + } + + @Override + public Result<Void> deleteDelegate(AuthzTrans trans, String userName) { + DelegateDAO.Data dd = new DelegateDAO.Data(); + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", userName).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + dd.user = userName; + Result<List<DelegateDAO.Data>> ddl; + if((ddl=ques.delegateDAO.read(trans, dd)).notOKorIsEmpty()) { + return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate"); + } + dd = ddl.value.get(0); + Result<Void> rv = ques.mayUser(trans, dd, Access.write); + if(rv.notOK()) { + return rv; + } + + return ques.delegateDAO.delete(trans, dd, false); + } + + @Override + public Result<DELGS> getDelegatesByUser(AuthzTrans trans, String user) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + DelegateDAO.Data ddd = new DelegateDAO.Data(); + ddd.user = user; + ddd.delegate = null; + Result<Void> rv = ques.mayUser(trans, ddd, Access.read); + if(rv.notOK()) { + return Result.err(rv); + } + + TimeTaken tt = trans.start("Get delegates for a user", Env.SUB); + + Result<List<DelegateDAO.Data>> dbDelgs = ques.delegateDAO.read(trans, user); + try { + if (dbDelgs.isOKhasData()) { + return mapper.delegate(dbDelgs.value); + } else { + return Result.err(Status.ERR_DelegateNotFound,"No Delegate found for [%s]",user); + } + } finally { + tt.done(); + } + } + + @Override + public Result<DELGS> getDelegatesByDelegate(AuthzTrans trans, String delegate) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Delegate", delegate).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + DelegateDAO.Data ddd = new DelegateDAO.Data(); + ddd.user = delegate; + Result<Void> rv = ques.mayUser(trans, ddd, Access.read); + if(rv.notOK()) { + return Result.err(rv); + } + + TimeTaken tt = trans.start("Get users for a delegate", Env.SUB); + + Result<List<DelegateDAO.Data>> dbDelgs = ques.delegateDAO.readByDelegate(trans, delegate); + try { + if (dbDelgs.isOKhasData()) { + return mapper.delegate(dbDelgs.value); + } else { + return Result.err(Status.ERR_DelegateNotFound,"Delegate [%s] is not delegating for anyone.",delegate); + } + } finally { + tt.done(); + } + } + +/*********************************** + * APPROVAL + ***********************************/ + private static final String APPR_FMT = "actor=%s, action=%s, operation=\"%s\", requestor=%s, delegator=%s"; + @Override + public Result<Void> updateApproval(AuthzTrans trans, APPROVALS approvals) { + Result<List<ApprovalDAO.Data>> rlad = mapper.approvals(approvals); + if(rlad.notOK()) { + return Result.err(rlad); + } + int numApprs = rlad.value.size(); + if(numApprs<1) { + return Result.err(Status.ERR_NoApprovals,"No Approvals sent for Updating"); + } + int numProcessed = 0; + String user = trans.user(); + + Result<List<ApprovalDAO.Data>> curr; + Lookup<List<ApprovalDAO.Data>> apprByTicket=null; + for(ApprovalDAO.Data updt : rlad.value) { + if(updt.ticket!=null) { + curr = ques.approvalDAO.readByTicket(trans, updt.ticket); + if(curr.isOKhasData()) { + final List<ApprovalDAO.Data> add = curr.value; + apprByTicket = new Lookup<List<ApprovalDAO.Data>>() { // Store a Pre-Lookup + @Override + public List<ApprovalDAO.Data> get(AuthzTrans trans, Object ... noop) { + return add; + } + }; + } + } else if(updt.id!=null) { + curr = ques.approvalDAO.read(trans, updt); + } else if(updt.approver!=null) { + curr = ques.approvalDAO.readByApprover(trans, updt.approver); + } else { + return Result.err(Status.ERR_BadData,"Approvals need ID, Ticket or Approval data to update"); + } + + if(curr.isOKhasData()) { + Map<String, Result<List<DelegateDAO.Data>>> delegateCache = new HashMap<String, Result<List<DelegateDAO.Data>>>(); + Map<UUID, FutureDAO.Data> futureCache = new HashMap<UUID, FutureDAO.Data>(); + FutureDAO.Data hasDeleted = new FutureDAO.Data(); + + for(ApprovalDAO.Data cd : curr.value) { + if("pending".equals(cd.status)) { + // Check for right record. Need ID, or (Ticket&Trans.User==Appr) + // If Default ID + boolean delegatedAction = ques.isDelegated(trans, user, cd.approver, delegateCache); + String delegator = cd.approver; + if(updt.id!=null || + (updt.ticket!=null && user.equals(cd.approver)) || + (updt.ticket!=null && delegatedAction)) { + if(updt.ticket.equals(cd.ticket)) { + Changed ch = new Changed(); + cd.id = ch.changed(cd.id,updt.id); +// cd.ticket = changed(cd.ticket,updt.ticket); + cd.user = ch.changed(cd.user,updt.user); + cd.approver = ch.changed(cd.approver,updt.approver); + cd.type = ch.changed(cd.type,updt.type); + cd.status = ch.changed(cd.status,updt.status); + cd.memo = ch.changed(cd.memo,updt.memo); + cd.operation = ch.changed(cd.operation,updt.operation); + cd.updated = ch.changed(cd.updated,updt.updated==null?new Date():updt.updated); + if(updt.status.equals("denied")) { + cd.last_notified = null; + } + if(cd.ticket!=null) { + FutureDAO.Data fdd = futureCache.get(cd.ticket); + if(fdd==null) { // haven't processed ticket yet + Result<FutureDAO.Data> rfdd = ques.futureDAO.readPrimKey(trans, cd.ticket); + if(rfdd.isOK()) { + fdd = rfdd.value; // null is ok + } else { + fdd = hasDeleted; + } + futureCache.put(cd.ticket, fdd); // processed this Ticket... don't do others on this ticket + } + if(fdd==hasDeleted) { // YES, by Object + cd.ticket = null; + cd.status = "ticketDeleted"; + ch.hasChanged(true); + } else { + FUTURE_OP fop = FUTURE_OP.toFO(cd.operation); + if(fop==null) { + trans.info().printf("Approval Status %s is not actionable",cd.status); + } else if(apprByTicket!=null) { + Result<OP_STATUS> rv = func.performFutureOp(trans, fop, fdd, apprByTicket,func.urDBLookup); + if (rv.isOK()) { + switch(rv.value) { + case E: + if (delegatedAction) { + trans.audit().printf(APPR_FMT,user,updt.status,cd.memo,cd.user,delegator); + } + futureCache.put(cd.ticket, hasDeleted); + break; + case D: + case L: + ch.hasChanged(true); + trans.audit().printf(APPR_FMT,user,rv.value.desc(),cd.memo,cd.user,delegator); + futureCache.put(cd.ticket, hasDeleted); + break; + default: + } + } else { + trans.info().log(rv.toString()); + } + } + + } + ++numProcessed; + } + if(ch.hasChanged()) { + ques.approvalDAO.update(trans, cd, true); + } + } + } + } + } + } + } + + if(numApprs==numProcessed) { + return Result.ok(); + } + return Result.err(Status.ERR_ActionNotCompleted,numProcessed + " out of " + numApprs + " completed"); + + } + + private static class Changed { + private boolean hasChanged = false; + + public<T> T changed(T src, T proposed) { + if(proposed==null || (src!=null && src.equals(proposed))) { + return src; + } + hasChanged=true; + return proposed; + } + + public void hasChanged(boolean b) { + hasChanged=b; + } + + public boolean hasChanged() { + return hasChanged; + } + } + + @Override + public Result<APPROVALS> getApprovalsByUser(AuthzTrans trans, String user) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByUser(trans, user); + if(rapd.isOK()) { + return mapper.approvals(rapd.value); + } else { + return Result.err(rapd); + } +} + + @Override + public Result<APPROVALS> getApprovalsByTicket(AuthzTrans trans, String ticket) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Ticket", ticket).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + UUID uuid; + try { + uuid = UUID.fromString(ticket); + } catch (IllegalArgumentException e) { + return Result.err(Status.ERR_BadData,e.getMessage()); + } + + Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByTicket(trans, uuid); + if(rapd.isOK()) { + return mapper.approvals(rapd.value); + } else { + return Result.err(rapd); + } + } + + @Override + public Result<APPROVALS> getApprovalsByApprover(AuthzTrans trans, String approver) { + final Validator v = new ServiceValidator(); + if(v.nullOrBlank("Approver", approver).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + List<ApprovalDAO.Data> listRapds = new ArrayList<ApprovalDAO.Data>(); + + Result<List<ApprovalDAO.Data>> myRapd = ques.approvalDAO.readByApprover(trans, approver); + if(myRapd.notOK()) { + return Result.err(myRapd); + } + + listRapds.addAll(myRapd.value); + + Result<List<DelegateDAO.Data>> delegatedFor = ques.delegateDAO.readByDelegate(trans, approver); + if (delegatedFor.isOK()) { + for (DelegateDAO.Data dd : delegatedFor.value) { + if (dd.expires.after(new Date())) { + String delegator = dd.user; + Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByApprover(trans, delegator); + if (rapd.isOK()) { + for (ApprovalDAO.Data d : rapd.value) { + if (!d.user.equals(trans.user())) { + listRapds.add(d); + } + } + } + } + } + } + + return mapper.approvals(listRapds); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#clearCache(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ + @Override + public Result<Void> cacheClear(AuthzTrans trans, String cname) { + if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) { + return ques.clearCache(trans,cname); + } + return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear", + trans.user(),ROOT_NS,CACHE,cname); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.Integer) + */ + @Override + public Result<Void> cacheClear(AuthzTrans trans, String cname, int[] segment) { + if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) { + Result<Void> v=null; + for(int i: segment) { + v=ques.cacheClear(trans,cname,i); + } + if(v!=null) { + return v; + } + } + return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear", + trans.user(),ROOT_NS,CACHE,cname); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.AuthzService#dbReset(org.onap.aaf.auth.env.test.AuthzTrans) + */ + @Override + public void dbReset(AuthzTrans trans) { + ques.historyDAO.reportPerhapsReset(trans, null); + } + +} + diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java new file mode 100644 index 00000000..01e18510 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java @@ -0,0 +1,768 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service; + +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.aaf.auth.dao.DAOException; +import org.onap.aaf.auth.dao.cass.NsType; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.mapper.Mapper; + +public interface AuthzService<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> { + public Mapper<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper(); + +/*********************************** + * NAMESPACE + ***********************************/ + /** + * + * @param trans + * @param user + * @param ns + * @return + * @throws DAOException + * @throws + */ + public Result<Void> createNS(AuthzTrans trans, REQUEST request, NsType type); + + /** + * + * @param trans + * @param ns + * @return + */ + public Result<Void> addAdminNS(AuthzTrans trans, String ns, String id); + + /** + * + * @param trans + * @param ns + * @return + */ + public Result<Void> delAdminNS(AuthzTrans trans, String ns, String id); + + /** + * + * @param trans + * @param ns + * @param id + * @return + */ + public Result<Void> addResponsibleNS(AuthzTrans trans, String ns, String id); + + /** + * + * @param trans + * @param ns + * @param id + * @return + */ + public Result<Void> delResponsibleNS(AuthzTrans trans, String ns, String id); + + /** + * + * @param trans + * @param ns + * @param key + * @param value + * @return + */ + public Result<Void> createNsAttrib(AuthzTrans trans, String ns, String key, String value); + + /** + * + * @param trans + * @param ns + * @param key + * @param value + * @return + */ + public Result<?> updateNsAttrib(AuthzTrans trans, String ns, String key, String value); + + /** + * + * @param trans + * @param ns + * @param key + * @return + */ + public Result<Void> deleteNsAttrib(AuthzTrans trans, String ns, String key); + + /** + * + * @param trans + * @param ns + * @param key + * @return + */ + public Result<KEYS> readNsByAttrib(AuthzTrans trans, String key); + + + /** + * + * @param trans + * @param ns + * @return + */ + public Result<NSS> getNSbyName(AuthzTrans trans, String ns); + + /** + * + * @param trans + * @param user + * @return + */ + public Result<NSS> getNSbyAdmin(AuthzTrans trans, String user, boolean full); + + /** + * + * @param trans + * @param user + * @return + */ + public Result<NSS> getNSbyResponsible(AuthzTrans trans, String user, boolean full); + + /** + * + * @param trans + * @param user + * @return + */ + public Result<NSS> getNSbyEither(AuthzTrans trans, String user, boolean full); + + /** + * + * @param trans + * @param parent + * @return + */ + public Result<NSS> getNSsChildren(AuthzTrans trans, String parent); + + /** + * + * @param trans + * @param req + * @return + */ + public Result<Void> updateNsDescription(AuthzTrans trans, REQUEST req); + + /** + * + * @param trans + * @param ns + * @param user + * @return + * @throws DAOException + */ + public Result<Void> deleteNS(AuthzTrans trans, String ns); + +/*********************************** + * PERM + ***********************************/ + /** + * + * @param trans + * @param rreq + * @return + * @throws DAOException + * @throws MappingException + */ + public Result<Void> createPerm(AuthzTrans trans, REQUEST rreq); + + /** + * + * @param trans + * @param childPerm + * @return + * @throws DAOException + */ + public Result<PERMS> getPermsByType(AuthzTrans trans, String perm); + + /** + * + * @param trans + * @param type + * @param instance + * @param action + * @return + */ + public Result<PERMS> getPermsByName(AuthzTrans trans, String type, + String instance, String action); + + /** + * Gets all the permissions for a user across all the roles it is assigned to + * @param userName + * @return + * @throws Exception + * @throws Exception + */ + public Result<PERMS> getPermsByUser(AuthzTrans trans, String userName); + + /** + * Gets all the permissions for a user across all the roles it is assigned to, filtered by NS (Scope) + * + * @param trans + * @param user + * @param scopes + * @return + */ + public Result<PERMS> getPermsByUserScope(AuthzTrans trans, String user, String[] scopes); + + + /** + * Gets all the permissions for a user across all the roles it is assigned to + * + * Add AAF Perms representing the "MayUser" calls if + * 1) Allowed + * 2) User has equivalent permission + * + * @param userName + * @return + * @throws Exception + * @throws Exception + */ + public Result<PERMS> getPermsByUser(AuthzTrans trans, PERMS perms, String userName); + + /** + * + * Gets all the permissions for a user across all the roles it is assigned to + * + * @param roleName + * @return + * @throws Exception + */ + public Result<PERMS> getPermsByRole(AuthzTrans trans, String roleName); + + /** + * + * @param trans + * @param ns + * @return + */ + public Result<PERMS> getPermsByNS(AuthzTrans trans, String ns); + + /** + * rename permission + * + * @param trans + * @param rreq + * @param isRename + * @param origType + * @param origInstance + * @param origAction + * @return + */ + public Result<Void> renamePerm(AuthzTrans trans, REQUEST rreq, String origType, String origInstance, String origAction); + + /** + * + * @param trans + * @param req + * @return + */ + public Result<Void> updatePermDescription(AuthzTrans trans, REQUEST req); + + /** + * + * @param trans + * @param from + * @return + */ + public Result<Void> resetPermRoles(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param from + * @return + * @throws Exception + */ + public Result<Void> deletePerm(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param user + * @param perm + * @param type + * @param action + * @return + * @throws Exception + */ + Result<Void> deletePerm(AuthzTrans trans, String perm, String type, String action); + +/*********************************** + * ROLE + ***********************************/ + /** + * + * @param trans + * @param user + * @param role + * @param approvers + * @return + * @throws DAOException + * @throws Exception + */ + public Result<Void> createRole(AuthzTrans trans, REQUEST req); + + /** + * + * @param trans + * @param role + * @return + */ + public Result<ROLES> getRolesByName(AuthzTrans trans, String role); + + /** + * + * @param trans + * @param user + * @return + * @throws DAOException + */ + public Result<ROLES> getRolesByUser(AuthzTrans trans, String user); + + /** + * + * @param trans + * @param user + * @return + */ + public Result<ROLES> getRolesByNS(AuthzTrans trans, String user); + + /** + * + * @param trans + * @param name + * @return + */ + public Result<ROLES> getRolesByNameOnly(AuthzTrans trans, String name); + + /** + * + * @param trans + * @param type + * @param instance + * @param action + * @return + */ + public Result<ROLES> getRolesByPerm(AuthzTrans trans, String type, String instance, String action); + + /** + * + * @param trans + * @param req + * @return + */ + public Result<Void> updateRoleDescription(AuthzTrans trans, REQUEST req); + + /** + * + * @param trans + * @param rreq + * @return + * @throws DAOException + */ + public Result<Void> addPermToRole(AuthzTrans trans, REQUEST rreq); + + + /** + * + * @param trans + * @param rreq + * @return + * @throws DAOException + */ + Result<Void> delPermFromRole(AuthzTrans trans, REQUEST rreq); + + /** + * Itemized key delete + * @param trans + * @param role + * @param type + * @param instance + * @param action + * @return + */ + public Result<Void> delPermFromRole(AuthzTrans trans, String role, String type, String instance, String action); + + /** + * + * @param trans + * @param user + * @param role + * @return + * @throws DAOException + * @throws MappingException + */ + public Result<Void> deleteRole(AuthzTrans trans, String role); + + /** + * + * @param trans + * @param req + * @return + */ + public Result<Void> deleteRole(AuthzTrans trans, REQUEST req); + +/*********************************** + * CRED + ***********************************/ + + /** + * + * @param trans + * @param from + * @return + */ + Result<Void> createUserCred(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param from + * @return + */ + Result<Void> changeUserCred(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param from + * @param days + * @return + */ + Result<Void> extendUserCred(AuthzTrans trans, REQUEST from, String days); + + /** + * + * @param trans + * @param ns + * @return + */ + public Result<USERS> getCredsByNS(AuthzTrans trans, String ns); + + /** + * + * @param trans + * @param id + * @return + */ + public Result<USERS> getCredsByID(AuthzTrans trans, String id); + + /** + * + * @param trans + * @param req + * @param id + * @return + */ + public Result<CERTS> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id); + + /** + * + * @param trans + * @param credReq + * @return + */ + public Result<Void> deleteUserCred(AuthzTrans trans, REQUEST credReq); + + /** + * + * @param trans + * @param user + * @return + * @throws Exception + */ + public Result<Date> doesCredentialMatch(AuthzTrans trans, REQUEST credReq); + + /** + * + * @param trans + * @param basicAuth + * @return + */ + public Result<Date> validateBasicAuth(AuthzTrans trans, String basicAuth); + + /** + * + * @param trans + * @param role + * @return + */ + public Result<USERS> getUsersByRole(AuthzTrans trans, String role); + + /** + * + * @param trans + * @param role + * @return + */ + public Result<USERS> getUserInRole(AuthzTrans trans, String user, String role); + + /** + * + * @param trans + * @param type + * @param instance + * @param action + * @return + */ + public Result<USERS> getUsersByPermission(AuthzTrans trans,String type, String instance, String action); + + + + +/*********************************** + * USER-ROLE + ***********************************/ + /** + * + * @param trans + * @param user + * @param request + * @return + * @throws Exception + */ + public Result<Void> createUserRole(AuthzTrans trans, REQUEST request); + + /** + * + * @param trans + * @param role + * @return + */ + public Result<USERROLES> getUserRolesByRole(AuthzTrans trans, String role); + + /** + * + * @param trans + * @param role + * @return + */ + public Result<USERROLES> getUserRolesByUser(AuthzTrans trans, String user); + + /** + * + * @param trans + * @param from + * @return + */ + public Result<Void> resetRolesForUser(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param from + * @return + */ + public Result<Void> resetUsersForRole(AuthzTrans trans, REQUEST from); + + /** + * + * @param trans + * @param user + * @param role + * @return + */ + public Result<Void> extendUserRole(AuthzTrans trans, String user, + String role); + + /** + * + * @param trans + * @param user + * @param usr + * @param role + * @return + * @throws DAOException + */ + public Result<Void> deleteUserRole(AuthzTrans trans, String usr, String role); + + + +/*********************************** + * HISTORY + ***********************************/ + /** + * + * @param trans + * @param user + * @param yyyymm + * @return + */ + public Result<HISTORY> getHistoryByUser(AuthzTrans trans, String user, int[] yyyymm, int sort); + + /** + * + * @param trans + * @param subj + * @param yyyymm + * @param sort + * @return + */ + public Result<HISTORY> getHistoryByRole(AuthzTrans trans, String subj, int[] yyyymm, int sort); + + /** + * + * @param trans + * @param subj + * @param yyyymm + * @param sort + * @return + */ + public Result<HISTORY> getHistoryByPerm(AuthzTrans trans, String subj, int[] yyyymm, int sort); + + /** + * + * @param trans + * @param subj + * @param yyyymm + * @param sort + * @return + */ + public Result<HISTORY> getHistoryByNS(AuthzTrans trans, String subj, int[] yyyymm, int sort); + +/*********************************** + * DELEGATE + ***********************************/ + /** + * + * @param trans + * @param delegates + * @return + * @throws Exception + */ + public Result<Void> createDelegate(AuthzTrans trans, REQUEST reqDelegate); + + /** + * + * @param trans + * @param delegates + * @return + * @throws Exception + */ + public Result<Void> updateDelegate(AuthzTrans trans, REQUEST reqDelegate); + + /** + * + * @param trans + * @param userName + * @param delegate + * @return + * @throws Exception + */ + public Result<Void> deleteDelegate(AuthzTrans trans, REQUEST reqDelegate); + + /** + * + * @param trans + * @param userName + * @return + */ + public Result<Void> deleteDelegate(AuthzTrans trans, String userName); + + /** + * + * @param trans + * @param user + * @return + * @throws Exception + */ + public Result<DELGS> getDelegatesByUser(AuthzTrans trans, String user); + + + /** + * + * @param trans + * @param delegate + * @return + */ + public Result<DELGS> getDelegatesByDelegate(AuthzTrans trans, String delegate); + +/*********************************** + * APPROVAL + ***********************************/ + /** + * + * @param trans + * @param user + * @param approver + * @param status + * @return + */ + public Result<Void> updateApproval(AuthzTrans trans, APPROVALS approvals); + + /** + * + * @param trans + * @param user + * @return + */ + public Result<APPROVALS> getApprovalsByUser(AuthzTrans trans, String user); + + /** + * + * @param trans + * @param ticket + * @return + */ + public Result<APPROVALS> getApprovalsByTicket(AuthzTrans trans, String ticket); + + /** + * + * @param trans + * @param approver + * @return + */ + public Result<APPROVALS> getApprovalsByApprover(AuthzTrans trans, String approver); + + /** + * + * @param trans + * @param cname + * @return + */ + public Result<Void> cacheClear(AuthzTrans trans, String cname); + + /** + * + * @param trans + * @param cname + * @param segment + * @return + */ + public Result<Void> cacheClear(AuthzTrans trans, String cname, int[] segment); + + /** + * + * @param trans + */ + public void dbReset(AuthzTrans trans); + + +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/Code.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/Code.java new file mode 100644 index 00000000..ba6e9d10 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/Code.java @@ -0,0 +1,44 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service; + +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.rserv.HttpCode; +import org.onap.aaf.auth.service.facade.AuthzFacade; + +public abstract class Code extends HttpCode<AuthzTrans, AuthzFacade> implements Cloneable { + public boolean useJSON; + + public Code(AuthzFacade facade, String description, boolean useJSON, String ... roles) { + super(facade, description, roles); + this.useJSON = useJSON; + } + + public <D extends Code> D clone(AuthzFacade facade, boolean useJSON) throws Exception { + @SuppressWarnings("unchecked") + D d = (D)clone(); + d.useJSON = useJSON; + d.context = facade; + return d; + } + +}
\ No newline at end of file diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/MayChange.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/MayChange.java new file mode 100644 index 00000000..7df43a4c --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/MayChange.java @@ -0,0 +1,33 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service; + +import org.onap.aaf.auth.layer.Result; + +/** + * There are several ways to determine if + * @author Jonathan + * + */ +public interface MayChange { + public Result<?> mayChange(); +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java new file mode 100644 index 00000000..79dda326 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java @@ -0,0 +1,92 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.rserv.HttpMethods; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; +import org.onap.aaf.cadi.Symm; + +/** + * API Apis + * @author Jonathan + * + */ +public class API_Api { + // Hide Public Constructor + private API_Api() {} + + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Service authzAPI, AuthzFacade facade) throws Exception { + //////// + // Overall APIs + /////// + authzAPI.route(HttpMethods.GET,"/api",API.API,new Code(facade,"Document API", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getAPI(trans,resp,authzAPI); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + + //////// + // Overall Examples + /////// + authzAPI.route(HttpMethods.GET,"/api/example/*",API.VOID,new Code(facade,"Document API", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String pathInfo = req.getPathInfo(); + int question = pathInfo.lastIndexOf('?'); + + pathInfo = pathInfo.substring(13, question<0?pathInfo.length():question);// IMPORTANT, this is size of "/api/example/" + String nameOrContextType=Symm.base64noSplit.decode(pathInfo); + Result<Void> r = context.getAPIExample(trans,resp,nameOrContextType, + question>=0 && "optional=true".equalsIgnoreCase(req.getPathInfo().substring(question+1)) + ); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + + } +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java new file mode 100644 index 00000000..e0c07684 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java @@ -0,0 +1,106 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.rserv.HttpMethods.GET; +import static org.onap.aaf.auth.rserv.HttpMethods.PUT; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; + +public class API_Approval { + // Hide Public Constructor + private API_Approval() {} + + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + + /** + * Get Approvals by User + */ + authzAPI.route(GET, "/authz/approval/user/:user",API.APPROVALS, + new Code(facade,"Get Approvals by User", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getApprovalsByUser(trans, resp, pathParam(req,"user")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + + /** + * Get Approvals by Ticket + */ + authzAPI.route(GET, "/authz/approval/ticket/:ticket",API.APPROVALS,new Code(facade,"Get Approvals by Ticket ", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getApprovalsByTicket(trans, resp, pathParam(req,"ticket")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + + /** + * Get Approvals by Approver + */ + authzAPI.route(GET, "/authz/approval/approver/:approver",API.APPROVALS,new Code(facade,"Get Approvals by Approver", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getApprovalsByApprover(trans, resp, pathParam(req,"approver")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + + + /** + * Update an approval + */ + authzAPI.route(PUT, "/authz/approval",API.APPROVALS,new Code(facade,"Update approvals", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.updateApproval(trans, req, resp); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + } +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java new file mode 100644 index 00000000..d31c9d01 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java @@ -0,0 +1,285 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.rserv.HttpMethods.DELETE; +import static org.onap.aaf.auth.rserv.HttpMethods.GET; +import static org.onap.aaf.auth.rserv.HttpMethods.POST; +import static org.onap.aaf.auth.rserv.HttpMethods.PUT; + +import java.security.Principal; +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.direct.DirectAAFUserPass; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.rserv.HttpMethods; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; +import org.onap.aaf.cadi.CredVal; +import org.onap.aaf.cadi.Symm; +import org.onap.aaf.cadi.principal.BasicPrincipal; +import org.onap.aaf.cadi.principal.X509Principal; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; + +/** + * Initialize All Dispatches related to Credentials (AUTHN) + * @author Jonathan + * + */ +public class API_Creds { + // Hide Public Interface + private API_Creds() {} + // needed to validate Creds even when already Authenticated x509 + /** + * TIME SENSITIVE APIs + * + * These will be first in the list + * + * @param env + * @param authzAPI + * @param facade + * @param directAAFUserPass + * @throws Exception + */ + public static void timeSensitiveInit(Env env, AAF_Service authzAPI, AuthzFacade facade, final DirectAAFUserPass directAAFUserPass) throws Exception { + /** + * Basic Auth, quick Validation + * + * Responds OK or NotAuthorized + */ + authzAPI.route(env, HttpMethods.GET, "/authn/basicAuth", new Code(facade,"Is given BasicAuth valid?",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Principal p = trans.getUserPrincipal(); + if (p instanceof BasicPrincipal) { + // the idea is that if call is made with this credential, and it's a BasicPrincipal, it's ok + // otherwise, it wouldn't have gotten here. + resp.setStatus(HttpStatus.OK_200); + } else if (p instanceof X509Principal) { + // have to check Basic Auth here, because it might be CSP. + String authz = req.getHeader("Authorization"); + if(authz.startsWith("Basic ")) { + String decoded = Symm.base64noSplit.decode(authz.substring(6)); + int colon = decoded.indexOf(':'); + TimeTaken tt = trans.start("Direct Validation", Env.REMOTE); + try { + if(directAAFUserPass.validate( + decoded.substring(0,colon), + CredVal.Type.PASSWORD , + decoded.substring(colon+1).getBytes(),trans)) { + + resp.setStatus(HttpStatus.OK_200); + } else { + // DME2 at this version crashes without some sort of response + resp.getOutputStream().print(""); + resp.setStatus(HttpStatus.FORBIDDEN_403); + } + } finally { + tt.done(); + } + } + } else if(p == null) { + trans.error().log("Transaction not Authenticated... no Principal"); + resp.setStatus(HttpStatus.FORBIDDEN_403); + } else { + trans.checkpoint("Basic Auth Check Failed: This wasn't a Basic Auth Trans"); + // For Auth Security questions, we don't give any info to client on why failed + resp.setStatus(HttpStatus.FORBIDDEN_403); + } + } + },"text/plain","*/*","*"); + + /** + * returns whether a given Credential is valid + */ + authzAPI.route(POST, "/authn/validate", API.CRED_REQ, new Code(facade,"Is given Credential valid?",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Date> r = context.doesCredentialMatch(trans, req, resp); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + // For Security, we don't give any info out on why failed, other than forbidden + // Can't do "401", because that is on the call itself + resp.setStatus(HttpStatus.FORBIDDEN_403); + } + } + }); + + /** + * returns whether a given Credential is valid + */ + authzAPI.route(GET, "/authn/cert/id/:id", API.CERTS, new Code(facade,"Get Cert Info by ID",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getCertInfoByID(trans, req, resp, pathParam(req,":id") ); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + // For Security, we don't give any info out on why failed, other than forbidden + resp.setStatus(HttpStatus.FORBIDDEN_403); + } + } + }); + + + + + } + + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * Create a new ID/Credential + */ + authzAPI.route(POST,"/authn/cred",API.CRED_REQ,new Code(facade,"Add a New ID/Credential", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.createUserCred(trans, req); + if(r.isOK()) { + resp.setStatus(HttpStatus.CREATED_201); + } else { + context.error(trans,resp,r); + } + } + }); + + /** + * gets all credentials by Namespace + */ + authzAPI.route(GET, "/authn/creds/ns/:ns", API.USERS, new Code(facade,"Get Creds for a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getCredsByNS(trans, resp, pathParam(req, "ns")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + + }); + + /** + * gets all credentials by ID + */ + authzAPI.route(GET, "/authn/creds/id/:id", API.USERS, new Code(facade,"Get Creds by ID",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getCredsByID(trans, resp, pathParam(req, "id")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + + }); + + + /** + * Update ID/Credential (aka reset) + */ + authzAPI.route(PUT,"/authn/cred",API.CRED_REQ,new Code(facade,"Update an ID/Credential", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + + Result<Void> r = context.changeUserCred(trans, req); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + + /** + * Extend ID/Credential + * This behavior will accelerate getting out of P1 outages due to ignoring renewal requests, or + * other expiration issues. + * + * Scenario is that people who are solving Password problems at night, are not necessarily those who + * know what the passwords are supposed to be. Also, changing Password, without changing Configurations + * using that password only exacerbates the P1 Issue. + */ + authzAPI.route(PUT,"/authn/cred/:days",API.CRED_REQ,new Code(facade,"Extend an ID/Credential", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.extendUserCred(trans, req, pathParam(req, "days")); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + + /** + * Delete a ID/Credential by Object + */ + authzAPI.route(DELETE,"/authn/cred",API.CRED_REQ,new Code(facade,"Delete a Credential", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.deleteUserCred(trans, req); + if(r.isOK()) { + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,r); + } + } + }); + + } +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Delegate.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Delegate.java new file mode 100644 index 00000000..067c9192 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Delegate.java @@ -0,0 +1,152 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.layer.Result.OK; +import static org.onap.aaf.auth.rserv.HttpMethods.DELETE; +import static org.onap.aaf.auth.rserv.HttpMethods.GET; +import static org.onap.aaf.auth.rserv.HttpMethods.POST; +import static org.onap.aaf.auth.rserv.HttpMethods.PUT; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; + +public class API_Delegate { + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * Add a delegate + */ + authzAPI.route(POST, "/authz/delegate",API.DELG_REQ,new Code(facade,"Add a Delegate", true) { + + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.createDelegate(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Update a delegate + */ + authzAPI.route(PUT, "/authz/delegate",API.DELG_REQ,new Code(facade,"Update a Delegate", true) { + + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.updateDelegate(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * DELETE delegates for a user + */ + authzAPI.route(DELETE, "/authz/delegate",API.DELG_REQ,new Code(facade,"Delete delegates for a user", true) { + + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.deleteDelegate(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * DELETE a delegate + */ + authzAPI.route(DELETE, "/authz/delegate/:user_name",API.VOID,new Code(facade,"Delete a Delegate", true) { + + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.deleteDelegate(trans, pathParam(req, "user_name")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Read who is delegating for User + */ + authzAPI.route(GET, "/authz/delegates/user/:user",API.DELGS,new Code(facade,"Get Delegates by User", true) { + + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getDelegatesByUser(trans, pathParam(req, "user"), resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Read for whom the User is delegating + */ + authzAPI.route(GET, "/authz/delegates/delegate/:delegate",API.DELGS,new Code(facade,"Get Delegates by Delegate", true) { + + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getDelegatesByDelegate(trans, pathParam(req, "delegate"), resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + } +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java new file mode 100644 index 00000000..9800ca42 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java @@ -0,0 +1,238 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.layer.Result.OK; +import static org.onap.aaf.auth.rserv.HttpMethods.GET; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.GregorianCalendar; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; + +/** + * Pull certain types of History Info + * + * Specify yyyymm as + * single - 201504 + * commas 201503,201504 + * ranges 201501-201504 + * combinations 201301,201401,201501-201504 + * + * @author Jonathan + * + */ +public class API_History { + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * Get History + */ + authzAPI.route(GET,"/authz/hist/user/:user",API.HISTORY,new Code(facade,"Get History by User", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + int[] years; + int descend; + try { + years = getYears(req); + descend = decending(req); + } catch(Exception e) { + context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); + return; + } + + Result<Void> r = context.getHistoryByUser(trans, resp, pathParam(req,":user"),years,descend); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Get History by NS + */ + authzAPI.route(GET,"/authz/hist/ns/:ns",API.HISTORY,new Code(facade,"Get History by Namespace", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + int[] years; + int descend; + try { + years = getYears(req); + descend = decending(req); + } catch(Exception e) { + context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); + return; + } + + Result<Void> r = context.getHistoryByNS(trans, resp, pathParam(req,":ns"),years,descend); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Get History by Role + */ + authzAPI.route(GET,"/authz/hist/role/:role",API.HISTORY,new Code(facade,"Get History by Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + int[] years; + int descend; + try { + years = getYears(req); + descend = decending(req); + } catch(Exception e) { + context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); + return; + } + + Result<Void> r = context.getHistoryByRole(trans, resp, pathParam(req,":role"),years,descend); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Get History by Perm Type + */ + authzAPI.route(GET,"/authz/hist/perm/:type",API.HISTORY,new Code(facade,"Get History by Perm Type", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + int[] years; + int descend; + try { + years = getYears(req); + descend = decending(req); + } catch(Exception e) { + context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); + return; + } + + Result<Void> r = context.getHistoryByPerm(trans, resp, pathParam(req,":type"),years,descend); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + } + + // Check if Ascending + private static int decending(HttpServletRequest req) { + if("true".equalsIgnoreCase(req.getParameter("desc")))return -1; + if("true".equalsIgnoreCase(req.getParameter("asc")))return 1; + return 0; + } + + // Get Common "yyyymm" parameter, or none + private static final SimpleDateFormat FMT = new SimpleDateFormat("yyyyMM"); + + private static int[] getYears(HttpServletRequest req) throws NumberFormatException { + String yyyymm = req.getParameter("yyyymm"); + ArrayList<Integer> ai= new ArrayList<Integer>(); + if(yyyymm==null) { + GregorianCalendar gc = new GregorianCalendar(); + // three months is the default + for(int i=0;i<3;++i) { + ai.add(Integer.parseInt(FMT.format(gc.getTime()))); + gc.add(GregorianCalendar.MONTH, -1); + } + } else { + for(String ym : yyyymm.split(",")) { + String range[] = ym.split("\\s*-\\s*"); + switch(range.length) { + case 0: + break; + case 1: + if(!ym.endsWith("-")) { + ai.add(getNum(ym)); + break; + } else { + range=new String[] {ym.substring(0, 6),FMT.format(new Date())}; + } + default: + GregorianCalendar gc = new GregorianCalendar(); + gc.set(GregorianCalendar.MONTH, Integer.parseInt(range[1].substring(4,6))-1); + gc.set(GregorianCalendar.YEAR, Integer.parseInt(range[1].substring(0,4))); + int end = getNum(FMT.format(gc.getTime())); + + gc.set(GregorianCalendar.MONTH, Integer.parseInt(range[0].substring(4,6))-1); + gc.set(GregorianCalendar.YEAR, Integer.parseInt(range[0].substring(0,4))); + for(int i=getNum(FMT.format(gc.getTime()));i<=end;gc.add(GregorianCalendar.MONTH, 1),i=getNum(FMT.format(gc.getTime()))) { + ai.add(i); + } + + } + } + } + if(ai.size()==0) { + throw new NumberFormatException(yyyymm + " is an invalid number or range"); + } + Collections.sort(ai); + int ym[] = new int[ai.size()]; + for(int i=0;i<ym.length;++i) { + ym[i]=ai.get(i); + } + return ym; + } + + private static int getNum(String n) { + if(n==null || n.length()!=6) throw new NumberFormatException(n + " is not in YYYYMM format"); + return Integer.parseInt(n); + } +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Mgmt.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Mgmt.java new file mode 100644 index 00000000..7eb9fd7b --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Mgmt.java @@ -0,0 +1,276 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.layer.Result.OK; +import static org.onap.aaf.auth.rserv.HttpMethods.DELETE; +import static org.onap.aaf.auth.rserv.HttpMethods.POST; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.common.Define; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; +import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf; +import org.onap.aaf.misc.env.Trans; + +/** + * User Role APIs + * @author Jonathan + * + */ +public class API_Mgmt { + + private static final String SUCCESS = "SUCCESS"; + private final static String PERM_DB_POOL_CLEAR=Define.ROOT_NS()+".db|pool|clear"; + private final static String PERM_DENY_IP = Define.ROOT_NS()+".deny|" + Define.ROOT_COMPANY() + "|ip"; + private final static String PERM_DENY_ID = Define.ROOT_NS()+".deny|" + Define.ROOT_COMPANY() + "|id"; + private final static String PERM_LOG_ID = Define.ROOT_NS()+".deny|" + Define.ROOT_COMPANY() + "|id"; + + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Service authzAPI, AuthzFacade facade) throws Exception { + + /** + * Clear Cache Segment + */ + authzAPI.route(DELETE,"/mgmt/cache/:area/:segments",API.VOID,new Code(facade,"Clear Cache by Segment", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.cacheClear(trans, pathParam(req,"area"), pathParam(req,"segments")); + switch(r.status) { + case OK: + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Clear Cache + */ + authzAPI.route(DELETE,"/mgmt/cache/:area",API.VOID,new Code(facade,"Clear Cache", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r; + String area; + r = context.cacheClear(trans, area=pathParam(req,"area")); + switch(r.status) { + case OK: + trans.audit().log("Cache " + area + " has been cleared by "+trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Clear DB Sessions + */ + authzAPI.route(DELETE,"/mgmt/dbsession",API.VOID,new Code(facade,"Clear DBSessions", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + try { + if(req.isUserInRole(PERM_DB_POOL_CLEAR)) { + context.dbReset(trans); + + trans.audit().log("DB Sessions have been cleared by "+trans.user()); + + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + return; + } + context.error(trans,resp,Result.err(Result.ERR_Denied,"%s is not allowed to clear dbsessions",trans.user())); + } catch(Exception e) { + trans.error().log(e, "clearing dbsession"); + context.error(trans,resp,Result.err(e)); + } + } + }); + + /** + * Deny an IP + */ + authzAPI.route(POST, "/mgmt/deny/ip/:ip", API.VOID, new Code(facade,"Deny IP",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String ip = pathParam(req,":ip"); + if(req.isUserInRole(PERM_DENY_IP)) { + if(DenialOfServiceTaf.denyIP(ip)) { + trans.audit().log(ip+" has been set to deny by "+trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + + resp.setStatus(HttpStatus.CREATED_201); + } else { + context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, + ip + " is already being denied")); + } + } else { + trans.audit().log(trans.user(),"has attempted to deny",ip,"without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to set IP Denial")); + } + } + }); + + /** + * Stop Denying an IP + */ + authzAPI.route(DELETE, "/mgmt/deny/ip/:ip", API.VOID, new Code(facade,"Stop Denying IP",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String ip = pathParam(req,":ip"); + if(req.isUserInRole(PERM_DENY_IP)) { + if(DenialOfServiceTaf.removeDenyIP(ip)) { + trans.audit().log(ip+" has been removed from denial by "+trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,Result.err(Status.ERR_NotFound, + ip + " is not on the denial list")); + } + } else { + trans.audit().log(trans.user(),"has attempted to remove",ip," from being denied without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to remove IP Denial")); + } + } + }); + + /** + * Deny an ID + */ + authzAPI.route(POST, "/mgmt/deny/id/:id", API.VOID, new Code(facade,"Deny ID",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String id = pathParam(req,":id"); + if(req.isUserInRole(PERM_DENY_ID)) { + if(DenialOfServiceTaf.denyID(id)) { + trans.audit().log(id+" has been set to deny by "+trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.CREATED_201); + } else { + context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, + id + " is already being denied")); + } + } else { + trans.audit().log(trans.user(),"has attempted to deny",id,"without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to set ID Denial")); + } + } + }); + + /** + * Stop Denying an ID + */ + authzAPI.route(DELETE, "/mgmt/deny/id/:id", API.VOID, new Code(facade,"Stop Denying ID",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String id = pathParam(req,":id"); + if(req.isUserInRole(PERM_DENY_ID)) { + if(DenialOfServiceTaf.removeDenyID(id)) { + trans.audit().log(id+" has been removed from denial by " + trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,Result.err(Status.ERR_NotFound, + id + " is not on the denial list")); + } + } else { + trans.audit().log(trans.user(),"has attempted to remove",id," from being denied without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to remove ID Denial")); + } + } + }); + + /** + * Deny an ID + */ + authzAPI.route(POST, "/mgmt/log/id/:id", API.VOID, new Code(facade,"Special Log ID",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String id = pathParam(req,":id"); + if(req.isUserInRole(PERM_LOG_ID)) { + if(Question.specialLogOn(trans,id)) { + trans.audit().log(id+" has been set to special Log by "+trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.CREATED_201); + } else { + context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, + id + " is already being special Logged")); + } + } else { + trans.audit().log(trans.user(),"has attempted to special Log",id,"without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to set ID special Logging")); + } + } + }); + + /** + * Stop Denying an ID + */ + authzAPI.route(DELETE, "/mgmt/log/id/:id", API.VOID, new Code(facade,"Stop Special Log ID",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + String id = pathParam(req,":id"); + if(req.isUserInRole(PERM_LOG_ID)) { + if(Question.specialLogOff(trans,id)) { + trans.audit().log(id+" has been removed from special Logging by " + trans.user()); + trans.checkpoint(SUCCESS,Trans.ALWAYS); + resp.setStatus(HttpStatus.OK_200); + } else { + context.error(trans,resp,Result.err(Status.ERR_NotFound, + id + " is not on the special Logging list")); + } + } else { + trans.audit().log(trans.user(),"has attempted to remove",id," from being special Logged without authorization"); + context.error(trans,resp,Result.err(Status.ERR_Denied, + trans.getUserPrincipal().getName() + " is not allowed to remove ID special Logging")); + } + } + }); + + + } +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Multi.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Multi.java new file mode 100644 index 00000000..d3fe4f1f --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Multi.java @@ -0,0 +1,65 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.layer.Result.OK; +import static org.onap.aaf.auth.rserv.HttpMethods.POST; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; + +public class API_Multi { + + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + + authzAPI.route(POST,"/authz/multi",API.VOID, new Code(facade,"Multiple Request API",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.addResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + case Status.ACC_Future: + resp.setStatus(HttpStatus.ACCEPTED_202); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + } + +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_NS.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_NS.java new file mode 100644 index 00000000..1087cd4d --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_NS.java @@ -0,0 +1,395 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.layer.Result.OK; +import static org.onap.aaf.auth.rserv.HttpMethods.DELETE; +import static org.onap.aaf.auth.rserv.HttpMethods.GET; +import static org.onap.aaf.auth.rserv.HttpMethods.POST; +import static org.onap.aaf.auth.rserv.HttpMethods.PUT; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.dao.cass.NsType; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; + +public class API_NS { + private static final String FULL = "full"; + private static final String TRUE = "true"; + + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * puts a new Namespace in Authz DB + * + * TESTCASES: TC_NS1, TC_NSdelete1 + */ + authzAPI.route(POST,"/authz/ns",API.NS_REQ, new Code(facade,"Create a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + NsType nst = NsType.fromString(req.getParameter("type")); + Result<Void> r = context.requestNS(trans, req, resp,nst); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + case Status.ACC_Future: + resp.setStatus(HttpStatus.ACCEPTED_202); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * removes a Namespace from Authz DB + * + * TESTCASES: TC_NS1, TC_NSdelete1 + */ + authzAPI.route(DELETE,"/authz/ns/:ns",API.VOID, new Code(facade,"Delete a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.deleteNS(trans, req, resp, pathParam(req,":ns")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Add an Admin in NS in Authz DB + * + * TESTCASES: TC_NS1 + */ + authzAPI.route(POST,"/authz/ns/:ns/admin/:id",API.VOID, new Code(facade,"Add an Admin to a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.addAdminToNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + case Status.ACC_Future: + resp.setStatus(HttpStatus.ACCEPTED_202); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Removes an Admin from Namespace in Authz DB + * + * TESTCASES: TC_NS1 + */ + authzAPI.route(DELETE,"/authz/ns/:ns/admin/:id",API.VOID, new Code(facade,"Remove an Admin from a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.delAdminFromNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Add an Admin in NS in Authz DB + * + * TESTCASES: TC_NS1 + */ + authzAPI.route(POST,"/authz/ns/:ns/responsible/:id",API.VOID, new Code(facade,"Add a Responsible Identity to a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.addResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + case Status.ACC_Future: + resp.setStatus(HttpStatus.ACCEPTED_202); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + + /** + * + */ + authzAPI.route(GET,"/authz/nss/:id",API.NSS, new Code(facade,"Return Information about Namespaces", true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.getNSsByName(trans, resp, pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Get all Namespaces where user is an admin + */ + authzAPI.route(GET,"/authz/nss/admin/:user",API.NSS, new Code(facade,"Return Namespaces where User is an Admin", true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.getNSsByAdmin(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL))); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Get all Namespaces where user is a responsible party + */ + authzAPI.route(GET,"/authz/nss/responsible/:user",API.NSS, new Code(facade,"Return Namespaces where User is Responsible", true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.getNSsByResponsible(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL))); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Get all Namespaces where user is an admin or owner + */ + authzAPI.route(GET,"/authz/nss/either/:user",API.NSS, new Code(facade,"Return Namespaces where User Admin or Owner", true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.getNSsByEither(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL))); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Get all children Namespaces + */ + authzAPI.route(GET,"/authz/nss/children/:id",API.NSS, new Code(facade,"Return Child Namespaces", true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.getNSsChildren(trans, resp, pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Set a description of a Namespace + */ + authzAPI.route(PUT,"/authz/ns",API.NS_REQ,new Code(facade,"Set a Description for a Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.updateNsDescription(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Removes an Owner from Namespace in Authz DB + * + * TESTCASES: TC_NS1 + */ + authzAPI.route(DELETE,"/authz/ns/:ns/responsible/:id",API.VOID, new Code(facade,"Remove a Responsible Identity from Namespace",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.delResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + authzAPI.route(POST,"/authz/ns/:ns/attrib/:key/:value",API.VOID, new Code(facade,"Add an Attribute from a Namespace",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.createAttribForNS(trans, resp, + pathParam(req,":ns"), + pathParam(req,":key"), + pathParam(req,":value")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + authzAPI.route(GET,"/authz/ns/attrib/:key",API.KEYS, new Code(facade,"get Ns Key List From Attribute",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.readNsByAttrib(trans, resp, pathParam(req,":key")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + authzAPI.route(PUT,"/authz/ns/:ns/attrib/:key/:value",API.VOID, new Code(facade,"update an Attribute from a Namespace",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.updAttribForNS(trans, resp, + pathParam(req,":ns"), + pathParam(req,":key"), + pathParam(req,":value")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + authzAPI.route(DELETE,"/authz/ns/:ns/attrib/:key",API.VOID, new Code(facade,"delete an Attribute from a Namespace",true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.delAttribForNS(trans, resp, + pathParam(req,":ns"), + pathParam(req,":key")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + } + + +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java new file mode 100644 index 00000000..c9795a5f --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java @@ -0,0 +1,297 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.layer.Result.OK; +import static org.onap.aaf.auth.rserv.HttpMethods.DELETE; +import static org.onap.aaf.auth.rserv.HttpMethods.GET; +import static org.onap.aaf.auth.rserv.HttpMethods.POST; +import static org.onap.aaf.auth.rserv.HttpMethods.PUT; + +import java.net.URLDecoder; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.misc.env.util.Split; + +public class API_Perms { + public static void timeSensitiveInit(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * gets all permissions by user name + */ + authzAPI.route(GET, "/authz/perms/user/:user", API.PERMS, new Code(facade,"Get Permissions by User",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + String scopes = req.getParameter("scopes"); + Result<Void> r; + if(scopes==null) { + r = context.getPermsByUser(trans, resp, pathParam(req, "user")); + } else { + r = context.getPermsByUserScope(trans, resp, pathParam(req, "user"),Split.split(':', scopes)); + } + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + + }); + + /** + * gets all permissions by user name + */ + authzAPI.route(POST, "/authz/perms/user/:user", API.PERMS, new Code(facade,"Get Permissions by User, Query AAF Perms",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getPermsByUserWithAAFQuery(trans, req, resp, pathParam(req, "user")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + + }); + + + } // end timeSensitiveInit + + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * Create a Permission + */ + authzAPI.route(POST,"/authz/perm",API.PERM_REQ,new Code(facade,"Create a Permission",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.createPerm(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * get details of Permission + */ + authzAPI.route(GET, "/authz/perms/:type/:instance/:action", API.PERMS, new Code(facade,"Get Permissions by Key",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getPermsByName(trans, resp, + pathParam(req, "type"), + URLDecoder.decode(pathParam(req, "instance"),Config.UTF_8), + pathParam(req, "action")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + + }); + + /** + * get children of Permission + */ + authzAPI.route(GET, "/authz/perms/:type", API.PERMS, new Code(facade,"Get Permissions by Type",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getPermsByType(trans, resp, pathParam(req, "type")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + + }); + + + /** + * gets all permissions by role name + */ + authzAPI.route(GET,"/authz/perms/role/:role",API.PERMS,new Code(facade,"Get Permissions by Role",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getPermsForRole(trans, resp, pathParam(req, "role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * gets all permissions by Namespace + */ + authzAPI.route(GET,"/authz/perms/ns/:ns",API.PERMS,new Code(facade,"Get PermsByNS",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getPermsByNS(trans, resp, pathParam(req, "ns")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Set a perm's description + */ + authzAPI.route(PUT,"/authz/perm",API.PERM_REQ,new Code(facade,"Set Description for Permission",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.updatePermDescription(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Update a permission with a rename + */ + authzAPI.route(PUT,"/authz/perm/:type/:instance/:action",API.PERM_REQ,new Code(facade,"Update a Permission",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.renamePerm(trans, req, resp, pathParam(req, "type"), + pathParam(req, "instance"), pathParam(req, "action")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Delete a Permission + */ + authzAPI.route(DELETE,"/authz/perm",API.PERM_REQ,new Code(facade,"Delete a Permission",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.deletePerm(trans,req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + + + + /** + * Delete a Permission + */ + authzAPI.route(DELETE,"/authz/perm/:name/:type/:action",API.PERM_KEY,new Code(facade,"Delete a Permission",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.deletePerm(trans, resp, + pathParam(req, ":name"), + pathParam(req, ":type"), + pathParam(req, ":action")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + } // end init +} + + + diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Roles.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Roles.java new file mode 100644 index 00000000..24259e16 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Roles.java @@ -0,0 +1,337 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.layer.Result.OK; +import static org.onap.aaf.auth.rserv.HttpMethods.DELETE; +import static org.onap.aaf.auth.rserv.HttpMethods.GET; +import static org.onap.aaf.auth.rserv.HttpMethods.POST; +import static org.onap.aaf.auth.rserv.HttpMethods.PUT; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; + +public class API_Roles { + public static void init(AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * puts a new role in Authz DB + */ + authzAPI.route(POST,"/authz/role",API.ROLE_REQ, new Code(facade,"Create Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.createRole(trans, req, resp); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + case Status.ACC_Future: + resp.setStatus(HttpStatus.ACCEPTED_202); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * get Role by name + */ + authzAPI.route(GET, "/authz/roles/:role", API.ROLES, new Code(facade,"GetRolesByFullName",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getRolesByName(trans, resp, pathParam(req, "role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + + }); + + + /** + * gets all Roles by user name + */ + authzAPI.route(GET, "/authz/roles/user/:name", API.ROLES, new Code(facade,"GetRolesByUser",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getRolesByUser(trans, resp, pathParam(req, "name")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + + }); + + /** + * gets all Roles by Namespace + */ + authzAPI.route(GET, "/authz/roles/ns/:ns", API.ROLES, new Code(facade,"GetRolesByNS",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getRolesByNS(trans, resp, pathParam(req, "ns")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * gets all Roles by Name without the Namespace + */ + authzAPI.route(GET, "/authz/roles/name/:name", API.ROLES, new Code(facade,"GetRolesByNameOnly",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.getRolesByNameOnly(trans, resp, pathParam(req, ":name")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Deletes a Role from Authz DB by Object + */ + authzAPI.route(DELETE,"/authz/role",API.ROLE_REQ, new Code(facade,"Delete Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.deleteRole(trans, req, resp); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + + } + ); + + + + /** + * Deletes a Role from Authz DB by Key + */ + authzAPI.route(DELETE,"/authz/role/:role",API.ROLE, new Code(facade,"Delete Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.deleteRole(trans, resp, pathParam(req,":role")); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + + } + ); + + + /** + * Add a Permission to a Role (Grant) + */ + authzAPI.route(POST,"/authz/role/perm",API.ROLE_PERM_REQ, new Code(facade,"Add Permission to Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.addPermToRole(trans, req, resp); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + default: + context.error(trans,resp,r); + } + } + } + ); + + /** + * Get all Roles by Permission + */ + authzAPI.route(GET,"/authz/roles/perm/:type/:instance/:action",API.ROLES,new Code(facade,"GetRolesByPerm",true) { + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.getRolesByPerm(trans, resp, + pathParam(req, "type"), + pathParam(req, "instance"), + pathParam(req, "action")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Set a role's description + */ + authzAPI.route(PUT,"/authz/role",API.ROLE_REQ,new Code(facade,"Set Description for role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.updateRoleDescription(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Set a permission's roles to roles given + */ + authzAPI.route(PUT,"/authz/role/perm",API.ROLE_PERM_REQ,new Code(facade,"Set a Permission's Roles",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + + Result<Void> r = context.resetPermRoles(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Delete a Permission from a Role + * With multiple perms + */ + authzAPI.route(DELETE,"/authz/role/:role/perm",API.ROLE_PERM_REQ, new Code(facade,"Delete Permission from Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.delPermFromRole(trans, req, resp); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + + /* + * Delete a Permission from a Role by key only + * / + authzAPI.route(DELETE,"/authz/role/:role/perm/:type/:instance/:action",API.ROLE_PERM_REQ, new Code(facade,"Delete Permission from Role",true) { + @Override + public void handle( + AuthzTrans trans, + HttpServletRequest req, + HttpServletResponse resp) throws Exception { + Result<Void> r = context.delPermFromRole(trans, resp, + pathParam(req,":role"), + pathParam(req,":type"), + pathParam(req,":instance"), + pathParam(req,":action")); + + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + */ + } +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_User.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_User.java new file mode 100644 index 00000000..26be2a07 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_User.java @@ -0,0 +1,133 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.layer.Result.OK; +import static org.onap.aaf.auth.rserv.HttpMethods.GET; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; + +/** + * User Role APIs + * @author Jonathan + * + */ +public class API_User { + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * get all Users who have Permission X + */ + authzAPI.route(GET,"/authz/users/perm/:type/:instance/:action",API.USERS,new Code(facade,"Get Users By Permission", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { +// trans.checkpoint(pathParam(req,"type") + " " +// + pathParam(req,"instance") + " " +// + pathParam(req,"action")); +// + Result<Void> r = context.getUsersByPermission(trans, resp, + pathParam(req, ":type"), + pathParam(req, ":instance"), + pathParam(req, ":action")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + + /** + * get all Users who have Role X + */ + authzAPI.route(GET,"/authz/users/role/:role",API.USERS,new Code(facade,"Get Users By Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getUsersByRole(trans, resp, pathParam(req, ":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Get User Role if exists + * @deprecated + */ + authzAPI.route(GET,"/authz/userRole/:user/:role",API.USERS,new Code(facade,"Get if User is In Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getUserInRole(trans, resp, pathParam(req,":user"),pathParam(req,":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Get User Role if exists + */ + authzAPI.route(GET,"/authz/users/:user/:role",API.USERS,new Code(facade,"Get if User is In Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getUserInRole(trans, resp, pathParam(req,":user"),pathParam(req,":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + + + } + +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java new file mode 100644 index 00000000..89550a71 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java @@ -0,0 +1,181 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.api; + +import static org.onap.aaf.auth.layer.Result.OK; +import static org.onap.aaf.auth.rserv.HttpMethods.DELETE; +import static org.onap.aaf.auth.rserv.HttpMethods.GET; +import static org.onap.aaf.auth.rserv.HttpMethods.POST; +import static org.onap.aaf.auth.rserv.HttpMethods.PUT; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpStatus; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.AAF_Service; +import org.onap.aaf.auth.service.Code; +import org.onap.aaf.auth.service.facade.AuthzFacade; +import org.onap.aaf.auth.service.mapper.Mapper.API; + +/** + * User Role APIs + * @author Jonathan + * + */ +public class API_UserRole { + /** + * Normal Init level APIs + * + * @param authzAPI + * @param facade + * @throws Exception + */ + public static void init(final AAF_Service authzAPI, AuthzFacade facade) throws Exception { + /** + * Request User Role Access + */ + authzAPI.route(POST,"/authz/userRole",API.USER_ROLE_REQ,new Code(facade,"Request User Role Access", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.requestUserRole(trans, req, resp); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.CREATED_201); + break; + default: + context.error(trans,resp,r); + } + } + }); + + + /** + * Get UserRoles by Role + */ + authzAPI.route(GET,"/authz/userRoles/role/:role",API.USER_ROLES,new Code(facade,"Get UserRoles by Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getUserRolesByRole(trans, resp, pathParam(req,":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Get UserRoles by User + */ + authzAPI.route(GET,"/authz/userRoles/user/:user",API.USER_ROLES,new Code(facade,"Get UserRoles by User", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.getUserRolesByUser(trans, resp, pathParam(req,":user")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + + /** + * Update roles attached to user in path + */ + authzAPI.route(PUT,"/authz/userRole/user",API.USER_ROLE_REQ,new Code(facade,"Update Roles for a user", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.resetRolesForUser(trans, resp, req); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + + /** + * Update users attached to role in path + */ + authzAPI.route(PUT,"/authz/userRole/role",API.USER_ROLE_REQ,new Code(facade,"Update Users for a role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.resetUsersForRole(trans, resp, req); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + /** + * Extend Expiration Date (according to Organizational rules) + */ + authzAPI.route(PUT, "/authz/userRole/extend/:user/:role", API.VOID, new Code(facade,"Extend Expiration", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.extendUserRoleExpiration(trans,resp,pathParam(req,":user"),pathParam(req,":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + + } + + }); + + + /** + * Create a new ID/Credential + */ + authzAPI.route(DELETE,"/authz/userRole/:user/:role",API.VOID,new Code(facade,"Delete User Role", true) { + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + Result<Void> r = context.deleteUserRole(trans, resp, pathParam(req,":user"),pathParam(req,":role")); + switch(r.status) { + case OK: + resp.setStatus(HttpStatus.OK_200); + break; + default: + context.error(trans,resp,r); + } + } + }); + + } +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java new file mode 100644 index 00000000..af375199 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java @@ -0,0 +1,269 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.facade; + +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.aaf.auth.dao.cass.NsType; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.rserv.RServlet; + +/** + * AuthzFacade + * This layer is responsible for covering the Incoming Messages, be they XML, JSON or just entries on the URL, + * and converting them to data that can be called on the Service Layer. + * + * Upon response, this layer, because it knew the incoming Data Formats (i.e. XML/JSON), the HTTP call types + * are set on "ContentType" on Response. + * + * Finally, we wrap the call in Time Stamps with explanation of what is happing for Audit trails. + * + * @author Jonathan + * + */ +public interface AuthzFacade { + public static final int PERM_DEPEND_424 = -1000; + public static final int ROLE_DEPEND_424 = -1001; + + /* + * Namespaces + */ + public abstract Result<Void> requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type); + + public abstract Result<Void> getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns); + + public abstract Result<Void> getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); + + public abstract Result<Void> getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); + + public abstract Result<Void> getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); + + public abstract Result<Void> getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String pathParam); + + public abstract Result<Void> addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + + public abstract Result<Void> delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + + public abstract Result<Void> addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + + public abstract Result<Void> delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + + public abstract Result<Void> updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns); + + // NS Attribs + public abstract Result<Void> createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value); + + public abstract Result<Void> readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key); + + public abstract Result<Void> updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value); + + public abstract Result<Void> delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key); + + /* + * Permissions + */ + public abstract Result<Void> createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> getPermsByName(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action); + + public abstract Result<Void> getPermsByUser(AuthzTrans trans, HttpServletResponse response, String user); + + public abstract Result<Void> getPermsByUserScope(AuthzTrans trans, HttpServletResponse resp, String user, String[] scopes); + + public abstract Result<Void> getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest request, HttpServletResponse response, String user); + + public abstract Result<Void> getPermsByType(AuthzTrans trans, HttpServletResponse resp, String type); + + public abstract Result<Void> getPermsForRole(AuthzTrans trans, HttpServletResponse response, String roleName); + + public abstract Result<Void> getPermsByNS(AuthzTrans trans, HttpServletResponse response, String ns); + + public abstract Result<Void> renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, + String type, String instance, String action); + + public abstract Result<Void> updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> deletePerm(AuthzTrans trans, HttpServletResponse resp, + String perm, String type, String action); + + /* + * Roles + */ + public abstract Result<Void> createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse response); + + public abstract Result<Void> getRolesByName(AuthzTrans trans,HttpServletResponse resp, String name); + + public abstract Result<Void> getRolesByNS(AuthzTrans trans, HttpServletResponse resp, String ns); + + public abstract Result<Void> getRolesByNameOnly(AuthzTrans trans, HttpServletResponse resp, String nameOnly); + + public abstract Result<Void> getRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user); + + public abstract Result<Void> getRolesByPerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action); + + public abstract Result<Void> updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> addPermToRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> delPermFromRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> delPermFromRole(AuthzTrans trans, HttpServletResponse resp, + String role, String type, String instance, String action); + + public abstract Result<Void> deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> deleteRole(AuthzTrans trans, HttpServletResponse resp, String role); + + /* + * Users + */ + + public abstract Result<Void> getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role); + + public abstract Result<Void> getUsersByPermission(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action); + + + + /* + * Delegates + */ + public abstract Result<Void> createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> deleteDelegate(AuthzTrans trans, String user); + + public abstract Result<Void> getDelegatesByUser(AuthzTrans trans, String userName, HttpServletResponse resp); + + public abstract Result<Void> getDelegatesByDelegate(AuthzTrans trans, String userName, HttpServletResponse resp); + + /* + * Credentials + */ + public abstract Result<Void> createUserCred(AuthzTrans trans, HttpServletRequest req); + + public abstract Result<Void> changeUserCred(AuthzTrans trans, HttpServletRequest req); + + public abstract Result<Void> extendUserCred(AuthzTrans trans, HttpServletRequest req, String days); + + public abstract Result<Void> getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns); + + public abstract Result<Void> getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id); + + public abstract Result<Void> deleteUserCred(AuthzTrans trans, HttpServletRequest req); + + public abstract Result<Void> validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth); + + public abstract Result<Date> doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + /* + * Miscellaneous + */ + /** + * Place Standard Messages based on HTTP Code onto Error Data Structure, and write to OutputStream + * Log message + */ + public abstract void error(AuthzTrans trans, HttpServletResponse response, Result<?> result); + + /* + * UserRole + */ + public abstract Result<Void> requestUserRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role); + + public abstract Result<Void> getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role); + + public abstract Result<Void> getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user); + + public abstract Result<Void> deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role); + + public abstract Result<Void> resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req); + + public abstract Result<Void> resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req); + + public abstract Result<Void> extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, + String role); + + /* + * Approval + */ + public abstract Result<Void> updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result<Void> getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user); + + public abstract Result<Void> getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket); + + public abstract Result<Void> getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver); + + + /* + * History + */ + public abstract Result<Void> getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort); + + public abstract Result<Void> getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); + + public abstract Result<Void> getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); + + public abstract Result<Void> getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); + + /* + * Cache + */ + public abstract Result<Void> cacheClear(AuthzTrans trans, String pathParam); + + public abstract Result<Void> cacheClear(AuthzTrans trans, String string,String segments); + + public abstract void dbReset(AuthzTrans trans); + + + + /* + * API + */ + public Result<Void> getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet<AuthzTrans> rservlet); + + public abstract Result<Void> getAPIExample(AuthzTrans trans, HttpServletResponse resp, String typeCode, boolean optional); + + public abstract Result<Void> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id); + + + + + + +}
\ No newline at end of file diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeFactory.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeFactory.java new file mode 100644 index 00000000..de8260f1 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeFactory.java @@ -0,0 +1,55 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.facade; + +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.auth.env.AuthzEnv; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.service.AuthzCassServiceImpl; +import org.onap.aaf.auth.service.mapper.Mapper_2_0; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Data; + + +public class AuthzFacadeFactory { + public static AuthzFacade_2_0 v2_0(AuthzEnv env, AuthzTrans trans, Data.TYPE type, Question question) throws APIException { + return new AuthzFacade_2_0(env, + new AuthzCassServiceImpl< + aaf.v2_0.Nss, + aaf.v2_0.Perms, + aaf.v2_0.Pkey, + aaf.v2_0.Roles, + aaf.v2_0.Users, + aaf.v2_0.UserRoles, + aaf.v2_0.Delgs, + aaf.v2_0.Certs, + aaf.v2_0.Keys, + aaf.v2_0.Request, + aaf.v2_0.History, + aaf.v2_0.Error, + aaf.v2_0.Approvals> + (trans,new Mapper_2_0(question),question), + type); + } + + +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java new file mode 100644 index 00000000..4895e26f --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java @@ -0,0 +1,2642 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.facade; + +import static org.onap.aaf.auth.dao.cass.Status.ERR_ChoiceNeeded; +import static org.onap.aaf.auth.dao.cass.Status.ERR_DelegateNotFound; +import static org.onap.aaf.auth.dao.cass.Status.ERR_DependencyExists; +import static org.onap.aaf.auth.dao.cass.Status.ERR_FutureNotRequested; +import static org.onap.aaf.auth.dao.cass.Status.ERR_InvalidDelegate; +import static org.onap.aaf.auth.dao.cass.Status.ERR_NsNotFound; +import static org.onap.aaf.auth.dao.cass.Status.ERR_PermissionNotFound; +import static org.onap.aaf.auth.dao.cass.Status.ERR_RoleNotFound; +import static org.onap.aaf.auth.dao.cass.Status.ERR_UserNotFound; +import static org.onap.aaf.auth.dao.cass.Status.ERR_UserRoleNotFound; +import static org.onap.aaf.auth.layer.Result.ERR_ActionNotCompleted; +import static org.onap.aaf.auth.layer.Result.ERR_Backend; +import static org.onap.aaf.auth.layer.Result.ERR_BadData; +import static org.onap.aaf.auth.layer.Result.ERR_ConflictAlreadyExists; +import static org.onap.aaf.auth.layer.Result.ERR_Denied; +import static org.onap.aaf.auth.layer.Result.ERR_NotFound; +import static org.onap.aaf.auth.layer.Result.ERR_NotImplemented; +import static org.onap.aaf.auth.layer.Result.ERR_Policy; +import static org.onap.aaf.auth.layer.Result.ERR_Security; +import static org.onap.aaf.auth.layer.Result.OK; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.aaf.auth.dao.cass.NsType; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.auth.env.AuthzEnv; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.FacadeImpl; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.rserv.RServlet; +import org.onap.aaf.auth.rserv.RouteReport; +import org.onap.aaf.auth.rserv.doc.ApiDoc; +import org.onap.aaf.auth.service.AuthzCassServiceImpl; +import org.onap.aaf.auth.service.AuthzService; +import org.onap.aaf.auth.service.mapper.Mapper; +import org.onap.aaf.auth.service.mapper.Mapper.API; +import org.onap.aaf.cadi.aaf.client.Examples; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Data; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Data.TYPE; +import org.onap.aaf.misc.env.util.Chrono; +import org.onap.aaf.misc.rosetta.Marshal; +import org.onap.aaf.misc.rosetta.env.RosettaDF; +import org.onap.aaf.misc.rosetta.env.RosettaData; + +import aaf.v2_0.Api; + +/** + * AuthzFacade + * + * This Service Facade encapsulates the essence of the API Service can do, and provides + * a single created object for elements such as RosettaDF. + * + * The Responsibilities of this class are to: + * 1) Interact with the Service Implementation (which might be supported by various kinds of Backend Storage) + * 2) Validate incoming data (if applicable) + * 3) Convert the Service response into the right Format, and mark the Content Type + * a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request. + * 4) Log Service info, warnings and exceptions as necessary + * 5) When asked by the API layer, this will create and write Error content to the OutputStream + * + * Note: This Class does NOT set the HTTP Status Code. That is up to the API layer, so that it can be + * clearly coordinated with the API Documentation + * + * @author Pavani & Jonathan + * + */ +public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> extends FacadeImpl implements AuthzFacade + { + private static final String FORBIDDEN = "Forbidden"; + private static final String NOT_FOUND = "Not Found"; + private static final String NOT_ACCEPTABLE = "Not Acceptable"; + private static final String GENERAL_SERVICE_ERROR = "General Service Error"; + private static final String NO_DATA = "***No Data***"; + private AuthzService<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> service = null; + private final RosettaDF<NSS> nssDF; + private final RosettaDF<PERMS> permsDF; + private final RosettaDF<ROLES> roleDF; + private final RosettaDF<USERS> usersDF; + private final RosettaDF<USERROLES> userrolesDF; + private final RosettaDF<CERTS> certsDF; + private final RosettaDF<DELGS> delgDF; + private final RosettaDF<REQUEST> permRequestDF; + private final RosettaDF<REQUEST> roleRequestDF; + private final RosettaDF<REQUEST> userRoleRequestDF; + private final RosettaDF<REQUEST> rolePermRequestDF; + private final RosettaDF<REQUEST> nsRequestDF; + private final RosettaDF<REQUEST> credRequestDF; + private final RosettaDF<REQUEST> delgRequestDF; + private final RosettaDF<HISTORY> historyDF; + private final RosettaDF<KEYS> keysDF; + + private final RosettaDF<ERR> errDF; + private final RosettaDF<APPROVALS> approvalDF; + // Note: Api is not different per Version + private final RosettaDF<Api> apiDF; + + + @SuppressWarnings("unchecked") + public AuthzFacadeImpl(AuthzEnv env, AuthzService<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> service, Data.TYPE dataType) throws APIException { + this.service = service; + (nssDF = env.newDataFactory(service.mapper().getClass(API.NSS))).in(dataType).out(dataType); + (permRequestDF = env.newDataFactory(service.mapper().getClass(API.PERM_REQ))).in(dataType).out(dataType); + (permsDF = env.newDataFactory(service.mapper().getClass(API.PERMS))).in(dataType).out(dataType); +// (permKeyDF = env.newDataFactory(service.mapper().getClass(API.PERM_KEY))).in(dataType).out(dataType); + (roleDF = env.newDataFactory(service.mapper().getClass(API.ROLES))).in(dataType).out(dataType); + (roleRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_REQ))).in(dataType).out(dataType); + (usersDF = env.newDataFactory(service.mapper().getClass(API.USERS))).in(dataType).out(dataType); + (userrolesDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLES))).in(dataType).out(dataType); + (certsDF = env.newDataFactory(service.mapper().getClass(API.CERTS))).in(dataType).out(dataType) + .rootMarshal((Marshal<CERTS>) service.mapper().getMarshal(API.CERTS)); + ; + (userRoleRequestDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLE_REQ))).in(dataType).out(dataType); + (rolePermRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_PERM_REQ))).in(dataType).out(dataType); + (nsRequestDF = env.newDataFactory(service.mapper().getClass(API.NS_REQ))).in(dataType).out(dataType); + (credRequestDF = env.newDataFactory(service.mapper().getClass(API.CRED_REQ))).in(dataType).out(dataType); + (delgRequestDF = env.newDataFactory(service.mapper().getClass(API.DELG_REQ))).in(dataType).out(dataType); + (historyDF = env.newDataFactory(service.mapper().getClass(API.HISTORY))).in(dataType).out(dataType); + ( keysDF = env.newDataFactory(service.mapper().getClass(API.KEYS))).in(dataType).out(dataType); + (delgDF = env.newDataFactory(service.mapper().getClass(API.DELGS))).in(dataType).out(dataType); + (approvalDF = env.newDataFactory(service.mapper().getClass(API.APPROVALS))).in(dataType).out(dataType); + (errDF = env.newDataFactory(service.mapper().getClass(API.ERROR))).in(dataType).out(dataType); + (apiDF = env.newDataFactory(Api.class)).in(dataType).out(dataType); + } + + public Mapper<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper() { + return service.mapper(); + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#error(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, int) + * + * Note: Conforms to AT&T TSS RESTful Error Structure + */ + @Override + public void error(AuthzTrans trans, HttpServletResponse response, Result<?> result) { + String msg = result.details==null?"%s":"%s - " + result.details.trim(); + String msgId; + String[] detail; + boolean hidemsg = false; + if(result.variables==null) { + detail = new String[1]; + } else { + int l = result.variables.length; + detail=new String[l+1]; + System.arraycopy(result.variables, 0, detail, 1, l); + } + //int httpstatus; + + switch(result.status) { + case ERR_ActionNotCompleted: + msgId = "SVC1202"; + detail[0] = "Accepted, Action not complete"; + response.setStatus(/*httpstatus=*/202); + break; + + case ERR_Policy: + msgId = "SVC3403"; + detail[0] = FORBIDDEN; + response.setStatus(/*httpstatus=*/403); + break; + case ERR_Security: + msgId = "SVC2403"; + detail[0] = FORBIDDEN; + response.setStatus(/*httpstatus=*/403); + break; + case ERR_Denied: + msgId = "SVC1403"; + detail[0] = FORBIDDEN; + response.setStatus(/*httpstatus=*/403); + break; + // This is still forbidden to directly impact, but can be Requested when passed + // with "request=true" query Param + case ERR_FutureNotRequested: + msgId = "SVC2403"; + detail[0] = msg; + response.setStatus(/*httpstatus=*/403); + break; + + case ERR_NsNotFound: + msgId = "SVC2404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_RoleNotFound: + msgId = "SVC3404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_PermissionNotFound: + msgId = "SVC4404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_UserNotFound: + msgId = "SVC5404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_UserRoleNotFound: + msgId = "SVC6404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_DelegateNotFound: + msgId = "SVC7404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + case ERR_NotFound: + msgId = "SVC1404"; + detail[0] = NOT_FOUND; + response.setStatus(/*httpstatus=*/404); + break; + + case ERR_InvalidDelegate: + msgId="SVC2406"; + detail[0] = NOT_ACCEPTABLE; + response.setStatus(/*httpstatus=*/406); + break; + case ERR_BadData: + msgId="SVC1406"; + detail[0] = NOT_ACCEPTABLE; + response.setStatus(/*httpstatus=*/406); + break; + + case ERR_ConflictAlreadyExists: + msgId = "SVC1409"; + detail[0] = "Conflict Already Exists"; + response.setStatus(/*httpstatus=*/409); + break; + + case ERR_DependencyExists: + msgId = "SVC1424"; + detail[0] = "Failed Dependency"; + response.setStatus(/*httpstatus=*/424); + break; + + case ERR_NotImplemented: + msgId = "SVC1501"; + detail[0] = "Not Implemented"; + response.setStatus(/*httpstatus=*/501); + break; + + case Status.ACC_Future: + msgId = "SVC1202"; + detail[0] = "Accepted for Future, pending Approvals"; + response.setStatus(/*httpstatus=*/202); + break; + case ERR_ChoiceNeeded: + msgId = "SVC1300"; + detail = result.variables; + response.setStatus(/*httpstatus=*/300); + break; + case ERR_Backend: + msgId = "SVC2500"; + detail[0] = GENERAL_SERVICE_ERROR; + response.setStatus(/*httpstatus=*/500); + hidemsg = true; + break; + + default: + msgId = "SVC1500"; + detail[0] = GENERAL_SERVICE_ERROR; + response.setStatus(/*httpstatus=*/500); + hidemsg = true; + break; + } + + try { + StringBuilder holder = new StringBuilder(); + ERR em = service.mapper().errorFromMessage(holder,msgId,msg,detail); + trans.checkpoint( + "ErrResp [" + + msgId + + "] " + + holder.toString(), + Env.ALWAYS); + if(hidemsg) { + holder.setLength(0); + em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); + } + errDF.newData(trans).load(em).to(response.getOutputStream()); + } catch (Exception e) { + trans.error().log(e,"unable to send response for",msg); + } + } + + /////////////////////////// + // Namespace + /////////////////////////// + public static final String CREATE_NS = "createNamespace"; + public static final String ADD_NS_ADMIN = "addNamespaceAdmin"; + public static final String DELETE_NS_ADMIN = "delNamespaceAdmin"; + public static final String ADD_NS_RESPONSIBLE = "addNamespaceResponsible"; + public static final String DELETE_NS_RESPONSIBLE = "delNamespaceResponsible"; + public static final String GET_NS_BY_NAME = "getNamespaceByName"; + public static final String GET_NS_BY_ADMIN = "getNamespaceByAdmin"; + public static final String GET_NS_BY_RESPONSIBLE = "getNamespaceByResponsible"; + public static final String GET_NS_BY_EITHER = "getNamespaceByEither"; + public static final String GET_NS_CHILDREN = "getNamespaceChildren"; + public static final String UPDATE_NS_DESC = "updateNamespaceDescription"; + public static final String DELETE_NS = "deleteNamespace"; + + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#createNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result<Void> requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type) { + TimeTaken tt = trans.start(CREATE_NS, Env.SUB|Env.ALWAYS); + try { + REQUEST request; + try { + Data<REQUEST> rd = nsRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,rd.asString()); + } + request = rd.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_NS); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result<Void> rp = service.createNS(trans,request,type); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,CREATE_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#addAdminToNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(ADD_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result<Void> rp = service.addAdminNS(trans,ns,id); + switch(rp.status) { + case OK: + //TODO Perms?? + setContentType(resp,nsRequestDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,ADD_NS_ADMIN); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#delAdminFromNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(DELETE_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result<Void> rp = service.delAdminNS(trans, ns, id); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_NS_ADMIN); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#addAdminToNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(ADD_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result<Void> rp = service.addResponsibleNS(trans,ns,id); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,ADD_NS_RESPONSIBLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#delAdminFromNS(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(DELETE_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result<Void> rp = service.delResponsibleNS(trans, ns, id); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_NS_RESPONSIBLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getNSsByName(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(GET_NS_BY_NAME + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result<NSS> rp = service.getNSbyName(trans, ns); + switch(rp.status) { + case OK: + RosettaData<NSS> data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_NAME); + return Result.err(e); + } finally { + tt.done(); + } + } + +// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getNSsByAdmin(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ + TimeTaken tt = trans.start(GET_NS_BY_ADMIN + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result<NSS> rp = service.getNSbyAdmin(trans, user, full); + switch(rp.status) { + case OK: + RosettaData<NSS> data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_ADMIN); + return Result.err(e); + } finally { + tt.done(); + } + } + +// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ + TimeTaken tt = trans.start(GET_NS_BY_RESPONSIBLE + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result<NSS> rp = service.getNSbyResponsible(trans, user, full); + switch(rp.status) { + case OK: + RosettaData<NSS> data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_RESPONSIBLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ + TimeTaken tt = trans.start(GET_NS_BY_EITHER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result<NSS> rp = service.getNSbyEither(trans, user, full); + + switch(rp.status) { + case OK: + RosettaData<NSS> data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_EITHER); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String parent){ + TimeTaken tt = trans.start(GET_NS_CHILDREN + ' ' + parent, Env.SUB|Env.ALWAYS); + try { + Result<NSS> rp = service.getNSsChildren(trans, parent); + switch(rp.status) { + case OK: + RosettaData<NSS> data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_CHILDREN); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_NS_DESC, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = nsRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,UPDATE_NS_DESC); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result<Void> rp = service.updateNsDescription(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_NS_DESC); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#requestNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result<Void> deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(DELETE_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result<Void> rp = service.deleteNS(trans,ns); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + private final static String NS_CREATE_ATTRIB = "nsCreateAttrib"; + private final static String NS_UPDATE_ATTRIB = "nsUpdateAttrib"; + private final static String READ_NS_BY_ATTRIB = "readNsByAttrib"; + private final static String NS_DELETE_ATTRIB = "nsDeleteAttrib"; + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#createAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) { + TimeTaken tt = trans.start(NS_CREATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS); + try { + Result<?> rp = service.createNsAttrib(trans,ns,key,value); + switch(rp.status) { + case OK: + setContentType(resp, keysDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,NS_CREATE_ATTRIB); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#readAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key) { + TimeTaken tt = trans.start(READ_NS_BY_ATTRIB + ' ' + key, Env.SUB|Env.ALWAYS); + try { + Result<KEYS> rp = service.readNsByAttrib(trans, key); + switch(rp.status) { + case OK: + RosettaData<KEYS> data = keysDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,keysDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,READ_NS_BY_ATTRIB); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#updAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) { + TimeTaken tt = trans.start(NS_UPDATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS); + try { + Result<?> rp = service.updateNsAttrib(trans,ns,key,value); + switch(rp.status) { + case OK: + setContentType(resp, keysDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,NS_UPDATE_ATTRIB); + return Result.err(e); + } finally { + tt.done(); + } + + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#delAttribForNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key) { + TimeTaken tt = trans.start(NS_DELETE_ATTRIB + ' ' + ns + ':'+key, Env.SUB|Env.ALWAYS); + try { + Result<?> rp = service.deleteNsAttrib(trans,ns,key); + switch(rp.status) { + case OK: + setContentType(resp, keysDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,NS_DELETE_ATTRIB); + return Result.err(e); + } finally { + tt.done(); + } + } + +// +// PERMISSION +// + public static final String CREATE_PERMISSION = "createPermission"; + public static final String GET_PERMS_BY_TYPE = "getPermsByType"; + public static final String GET_PERMS_BY_NAME = "getPermsByName"; + public static final String GET_PERMISSIONS_BY_USER = "getPermissionsByUser"; + public static final String GET_PERMISSIONS_BY_USER_SCOPE = "getPermissionsByUserScope"; + public static final String GET_PERMISSIONS_BY_USER_WITH_QUERY = "getPermissionsByUserWithQuery"; + public static final String GET_PERMISSIONS_BY_ROLE = "getPermissionsByRole"; + public static final String GET_PERMISSIONS_BY_NS = "getPermissionsByNS"; + public static final String UPDATE_PERMISSION = "updatePermission"; + public static final String UPDATE_PERM_DESC = "updatePermissionDescription"; + public static final String SET_PERMISSION_ROLES_TO = "setPermissionRolesTo"; + public static final String DELETE_PERMISSION = "deletePermission"; + + /* + * (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#createOrUpdatePerm(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start( CREATE_PERMISSION, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_PERMISSION); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result<Void> rp = service.createPerm(trans,rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,CREATE_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getChildPerms(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getPermsByType(AuthzTrans trans, HttpServletResponse resp, String perm) { + TimeTaken tt = trans.start(GET_PERMS_BY_TYPE + ' ' + perm, Env.SUB|Env.ALWAYS); + try { + + Result<PERMS> rp = service.getPermsByType(trans, perm); + switch(rp.status) { + case OK: + RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMS_BY_TYPE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> getPermsByName(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action) { + + TimeTaken tt = trans.start(GET_PERMS_BY_NAME + ' ' + type + + '|' + instance + '|' + action, Env.SUB|Env.ALWAYS); + try { + + Result<PERMS> rp = service.getPermsByName(trans, type, instance, action); + switch(rp.status) { + case OK: + RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMS_BY_TYPE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getPermsByUser(AuthzTrans trans, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result<PERMS> rp = service.getPermsByUser(trans, user); + switch(rp.status) { + case OK: + RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_USER, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getPermsByUserScope(AuthzTrans trans, HttpServletResponse resp, String user, String[] scopes) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER_SCOPE + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result<PERMS> rp = service.getPermsByUserScope(trans, user, scopes); + switch(rp.status) { + case OK: + RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_USER_SCOPE, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER_WITH_QUERY + ' ' + user, Env.SUB|Env.ALWAYS); + try { + PERMS perms; + try { + RosettaData<PERMS> data = permsDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + perms = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,GET_PERMISSIONS_BY_USER_WITH_QUERY); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result<PERMS> rp = service.getPermsByUser(trans, perms, user); + switch(rp.status) { + case OK: + RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_USER_WITH_QUERY , user); + return Result.err(e); + } finally { + tt.done(); + } + } + + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getPermissionsForRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getPermsForRole(AuthzTrans trans, HttpServletResponse resp, String roleName) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_ROLE + ' ' + roleName, Env.SUB|Env.ALWAYS); + try { + Result<PERMS> rp = service.getPermsByRole(trans, roleName); + switch(rp.status) { + case OK: + RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> getPermsByNS(AuthzTrans trans,HttpServletResponse resp,String ns) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result<PERMS> rp = service.getPermsByNS(trans, ns); + switch(rp.status) { + case OK: + RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#createOrUpdatePerm(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, + String origType, String origInstance, String origAction) { + String cmdDescription = UPDATE_PERMISSION; + TimeTaken tt = trans.start( cmdDescription + ' ' + origType + ' ' + origInstance + ' ' + origAction, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,cmdDescription); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result<Void> rp = service.renamePerm(trans,rreq, origType, origInstance, origAction); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,cmdDescription); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_PERM_DESC, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,UPDATE_PERM_DESC); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result<Void> rp = service.updatePermDescription(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_PERM_DESC); + return Result.err(e); + } finally { + tt.done(); + } + } + + + @Override + public Result<Void> resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(SET_PERMISSION_ROLES_TO, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = rolePermRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN, SET_PERMISSION_ROLES_TO); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result<Void> rp = service.resetPermRoles(trans, rreq); + + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,SET_PERMISSION_ROLES_TO); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_PERMISSION, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,DELETE_PERMISSION); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + + Result<Void> rp = service.deletePerm(trans,rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> deletePerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action) { + TimeTaken tt = trans.start(DELETE_PERMISSION + type + ' ' + instance + ' ' + action, Env.SUB|Env.ALWAYS); + try { + Result<Void> rp = service.deletePerm(trans,type,instance,action); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + public static final String CREATE_ROLE = "createRole"; + public static final String GET_ROLES_BY_USER = "getRolesByUser"; + public static final String GET_ROLES_BY_NS = "getRolesByNS"; + public static final String GET_ROLES_BY_NAME_ONLY = "getRolesByNameOnly"; + public static final String GET_ROLES_BY_NAME = "getRolesByName"; + public static final String GET_ROLES_BY_PERM = "getRolesByPerm"; + public static final String UPDATE_ROLE_DESC = "updateRoleDescription"; + public static final String ADD_PERM_TO_ROLE = "addPermissionToRole"; + public static final String DELETE_PERM_FROM_ROLE = "deletePermissionFromRole"; + public static final String UPDATE_MGTPERM_ROLE = "updateMgtPermRole"; + public static final String DELETE_ROLE = "deleteRole"; + public static final String GET_CERT_BY_ID = "getCertByID"; + + @Override + public Result<Void> createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(CREATE_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = roleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result<Void> rp = service.createRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,roleRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,CREATE_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getRolesByName(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getRolesByName(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(GET_ROLES_BY_NAME + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result<ROLES> rp = service.getRolesByName(trans, role); + switch(rp.status) { + case OK: + RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,roleDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_NAME); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getRolesByUser(AuthzTrans trans,HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_ROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result<ROLES> rp = service.getRolesByUser(trans, user); + switch(rp.status) { + case OK: + RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,roleDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_USER, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getRolesByNS(AuthzTrans trans,HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(GET_ROLES_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result<ROLES> rp = service.getRolesByNS(trans, ns); + switch(rp.status) { + case OK: + if(!rp.isEmpty()) { + RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + } else { + Question.logEncryptTrace(trans, NO_DATA); + } + setContentType(resp,roleDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getRolesByNameOnly(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getRolesByNameOnly(AuthzTrans trans,HttpServletResponse resp, String nameOnly) { + TimeTaken tt = trans.start(GET_ROLES_BY_NAME_ONLY + ' ' + nameOnly, Env.SUB|Env.ALWAYS); + try { + Result<ROLES> rp = service.getRolesByNameOnly(trans, nameOnly); + switch(rp.status) { + case OK: + if(!rp.isEmpty()) { + RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + } else { + Question.logEncryptTrace(trans, NO_DATA); + } + setContentType(resp,roleDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_NAME_ONLY); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getRolesByPerm(AuthzTrans trans,HttpServletResponse resp, String type, String instance, String action) { + TimeTaken tt = trans.start(GET_ROLES_BY_PERM + type +' '+instance+' '+action, Env.SUB|Env.ALWAYS); + try { + Result<ROLES> rp = service.getRolesByPerm(trans, type,instance,action); + switch(rp.status) { + case OK: + RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,roleDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_PERM); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#updateDescription(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result<Void> updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_ROLE_DESC, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = roleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,UPDATE_ROLE_DESC); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result<Void> rp = service.updateRoleDescription(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,roleRequestDF.getOutType()); + return Result.ok(); + default: + return rp; + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_ROLE_DESC); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> addPermToRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(ADD_PERM_TO_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = rolePermRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,ADD_PERM_TO_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result<Void> rp = service.addPermToRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,ADD_PERM_TO_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> delPermFromRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_PERM_FROM_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = rolePermRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,DELETE_PERM_FROM_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result<Void> rp = service.delPermFromRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERM_FROM_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#delPermFromRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> delPermFromRole(AuthzTrans trans, HttpServletResponse resp, String role, String type, + String instance, String action) { + TimeTaken tt = trans.start(DELETE_PERM_FROM_ROLE, Env.SUB|Env.ALWAYS); + try { + Result<Void> rp = service.delPermFromRole(trans, role, type, instance, action); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERM_FROM_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> deleteRole(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(DELETE_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result<Void> rp = service.deleteRole(trans, role); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = roleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result<Void> rp = service.deleteRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + public static final String CREATE_CRED = "createUserCred"; + private static final String GET_CREDS_BY_NS = "getCredsByNS"; + private static final String GET_CREDS_BY_ID = "getCredsByID"; + public static final String UPDATE_CRED = "updateUserCred"; + public static final String EXTEND_CRED = "extendUserCred"; + public static final String DELETE_CRED = "deleteUserCred"; + public static final String DOES_CRED_MATCH = "doesCredMatch"; + public static final String VALIDATE_BASIC_AUTH = "validateBasicAuth"; + + + + @Override + /** + * Create Credential + * + */ + public Result<Void> createUserCred(AuthzTrans trans, HttpServletRequest req) { + TimeTaken tt = trans.start(CREATE_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + return service.createUserCred(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,CREATE_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> changeUserCred(AuthzTrans trans, HttpServletRequest req) { + TimeTaken tt = trans.start(UPDATE_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.changeUserCred(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#extendUserCred(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, int) + */ + @Override + public Result<Void> extendUserCred(AuthzTrans trans, HttpServletRequest req, String days) { + TimeTaken tt = trans.start(EXTEND_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.extendUserCred(trans, data.asObject(), days); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,EXTEND_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(GET_CREDS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + + try { + Result<USERS> ru = service.getCredsByNS(trans,ns); + switch(ru.status) { + case OK: + RosettaData<USERS> data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans,trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_CREDS_BY_NS); + return Result.err(e); + } finally { + tt.done(); + } + + } + + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getCredsByID(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id) { + TimeTaken tt = trans.start(GET_CREDS_BY_ID + ' ' + id, Env.SUB|Env.ALWAYS); + + try { + Result<USERS> ru = service.getCredsByID(trans,id); + switch(ru.status) { + case OK: + RosettaData<USERS> data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_CREDS_BY_ID); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result<Void> deleteUserCred(AuthzTrans trans, HttpServletRequest req) { + TimeTaken tt = trans.start(DELETE_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.deleteUserCred(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,DELETE_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + + @Override + public Result<Date> doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DOES_CRED_MATCH, Env.SUB|Env.ALWAYS); + try { + RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.doesCredentialMatch(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (IOException e) { + trans.error().log(e,IN,DOES_CRED_MATCH); + return Result.err(e); + } finally { + tt.done(); + } + } + + + @Override + public Result<Void> validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth) { + TimeTaken tt = trans.start(VALIDATE_BASIC_AUTH, Env.SUB|Env.ALWAYS); + try { + Result<Date> result = service.validateBasicAuth(trans,basicAuth); + switch(result.status){ + case OK: + resp.getOutputStream().write(Chrono.utcStamp(result.value).getBytes()); + return Result.ok(); + } + return Result.err(result); + } catch (Exception e) { + trans.error().log(e,IN,VALIDATE_BASIC_AUTH); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getCertInfoByID(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id) { + TimeTaken tt = trans.start(GET_CERT_BY_ID, Env.SUB|Env.ALWAYS); + try { + Result<CERTS> rci = service.getCertInfoByID(trans,req,id); + + switch(rci.status) { + case OK: + if(Question.willSpecialLog(trans, trans.user())) { + RosettaData<CERTS> data = certsDF.newData(trans).load(rci.value); + Question.logEncryptTrace(trans,data.asString()); + data.to(resp.getOutputStream()); + } else { + certsDF.direct(trans, rci.value, resp.getOutputStream()); + } + setContentType(resp,certsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rci); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_CERT_BY_ID); + return Result.err(e); + } finally { + tt.done(); + } + } + + public static final String CREATE_DELEGATE = "createDelegate"; + public static final String UPDATE_DELEGATE = "updateDelegate"; + public static final String DELETE_DELEGATE = "deleteDelegate"; + public static final String GET_DELEGATE_USER = "getDelegatesByUser"; + public static final String GET_DELEGATE_DELG = "getDelegatesByDelegate"; + + @Override + public Result<Void> createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(CREATE_DELEGATE, Env.SUB|Env.ALWAYS); + try { + Data<REQUEST> data = delgRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.createDelegate(trans, data.asObject()); + } catch (Exception e) { + trans.error().log(e,IN,CREATE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_DELEGATE, Env.SUB|Env.ALWAYS); + try { + Data<REQUEST> data = delgRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.updateDelegate(trans, data.asObject()); + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_DELEGATE, Env.SUB|Env.ALWAYS); + try { + Data<REQUEST> data = delgRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.deleteDelegate(trans, data.asObject()); + } catch (Exception e) { + trans.error().log(e,IN,DELETE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> deleteDelegate(AuthzTrans trans, String userName) { + TimeTaken tt = trans.start(DELETE_DELEGATE + ' ' + userName, Env.SUB|Env.ALWAYS); + try { + return service.deleteDelegate(trans, userName); + } catch (Exception e) { + trans.error().log(e,IN,DELETE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> getDelegatesByUser(AuthzTrans trans, String user, HttpServletResponse resp) { + TimeTaken tt = trans.start(GET_DELEGATE_USER, Env.SUB|Env.ALWAYS); + try { + Result<DELGS> rd = service.getDelegatesByUser(trans, user); + + switch(rd.status) { + case OK: + RosettaData<DELGS> data = delgDF.newData(trans).load(rd.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,delgDF.getOutType()); + return Result.ok(); + default: + return Result.err(rd); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_DELEGATE_USER); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> getDelegatesByDelegate(AuthzTrans trans, String delegate, HttpServletResponse resp) { + TimeTaken tt = trans.start(GET_DELEGATE_DELG, Env.SUB|Env.ALWAYS); + try { + Result<DELGS> rd = service.getDelegatesByDelegate(trans, delegate); + switch(rd.status) { + case OK: + RosettaData<DELGS> data = delgDF.newData(trans).load(rd.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,delgDF.getOutType()); + return Result.ok(); + default: + return Result.err(rd); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_DELEGATE_DELG); + return Result.err(e); + } finally { + tt.done(); + } + } + + private static final String REQUEST_USER_ROLE = "createUserRole"; + private static final String GET_USERROLES = "getUserRoles"; + private static final String GET_USERROLES_BY_ROLE = "getUserRolesByRole"; + private static final String GET_USERROLES_BY_USER = "getUserRolesByUser"; + private static final String SET_ROLES_FOR_USER = "setRolesForUser"; + private static final String SET_USERS_FOR_ROLE = "setUsersForRole"; + private static final String EXTEND_USER_ROLE = "extendUserRole"; + private static final String DELETE_USER_ROLE = "deleteUserRole"; + @Override + public Result<Void> requestUserRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(REQUEST_USER_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST request; + try { + Data<REQUEST> data = userRoleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + request = data.asObject(); + } catch(APIException e) { + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result<Void> rp = service.createUserRole(trans,request); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,REQUEST_USER_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) { + TimeTaken tt = trans.start(GET_USERROLES + ' ' + user + '|' + role, Env.SUB|Env.ALWAYS); + try { + Result<USERS> ru = service.getUserInRole(trans,user,role); + switch(ru.status) { + case OK: + RosettaData<USERS> data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERROLES); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result<Void> getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_USERROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result<USERROLES> ru = service.getUserRolesByUser(trans,user); + switch(ru.status) { + case OK: + RosettaData<USERROLES> data = userrolesDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERROLES_BY_USER); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result<Void> getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(GET_USERROLES_BY_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result<USERROLES> ru = service.getUserRolesByRole(trans,role); + switch(ru.status) { + case OK: + RosettaData<USERROLES> data = userrolesDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + setCacheControlOff(resp); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERROLES_BY_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + + } + + + @Override + public Result<Void> resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) { + TimeTaken tt = trans.start(SET_USERS_FOR_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = userRoleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN, SET_USERS_FOR_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result<Void> rp = service.resetUsersForRole(trans, rreq); + + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,SET_USERS_FOR_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result<Void> resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) { + TimeTaken tt = trans.start(SET_ROLES_FOR_USER, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData<REQUEST> data = userRoleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN, SET_ROLES_FOR_USER); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result<Void> rp = service.resetRolesForUser(trans, rreq); + + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,SET_ROLES_FOR_USER); + return Result.err(e); + } finally { + tt.done(); + } + + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#extendUserRoleExpiration(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, String role) { + TimeTaken tt = trans.start(EXTEND_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS); + try { + return service.extendUserRole(trans,user,role); + } catch (Exception e) { + trans.error().log(e,IN,EXTEND_USER_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) { + TimeTaken tt = trans.start(DELETE_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result<Void> rp = service.deleteUserRole(trans,user,role); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_USER_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + private static final String UPDATE_APPROVAL = "updateApproval"; + private static final String GET_APPROVALS_BY_USER = "getApprovalsByUser."; + private static final String GET_APPROVALS_BY_TICKET = "getApprovalsByTicket."; + private static final String GET_APPROVALS_BY_APPROVER = "getApprovalsByApprover."; + + @Override + public Result<Void> updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_APPROVAL, Env.SUB|Env.ALWAYS); + try { + Data<APPROVALS> data = approvalDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + Result<Void> rp = service.updateApproval(trans, data.asObject()); + + switch(rp.status) { + case OK: + setContentType(resp,approvalDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_APPROVAL); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_APPROVALS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result<APPROVALS> rp = service.getApprovalsByUser(trans, user); + switch(rp.status) { + case OK: + RosettaData<APPROVALS> data = approvalDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_APPROVALS_BY_USER, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver) { + TimeTaken tt = trans.start(GET_APPROVALS_BY_APPROVER + ' ' + approver, Env.SUB|Env.ALWAYS); + try { + Result<APPROVALS> rp = service.getApprovalsByApprover(trans, approver); + switch(rp.status) { + case OK: + RosettaData<APPROVALS> data = approvalDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_APPROVALS_BY_APPROVER,approver); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result<Void> getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket) { + TimeTaken tt = trans.start(GET_APPROVALS_BY_TICKET, Env.SUB|Env.ALWAYS); + try { + Result<APPROVALS> rp = service.getApprovalsByTicket(trans, ticket); + switch(rp.status) { + case OK: + RosettaData<APPROVALS> data = approvalDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_APPROVALS_BY_TICKET); + return Result.err(e); + } finally { + tt.done(); + } + } + + + + public static final String GET_USERS_PERMISSION = "getUsersByPermission"; + public static final String GET_USERS_ROLE = "getUsersByRole"; + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getUsersByRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(GET_USERS_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result<USERS> ru = service.getUsersByRole(trans,role); + switch(ru.status) { + case OK: + RosettaData<USERS> data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERS_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getUsersByPermission(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public Result<Void> getUsersByPermission(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action) { + TimeTaken tt = trans.start(GET_USERS_PERMISSION + ' ' + type + ' ' + instance + ' ' +action, Env.SUB|Env.ALWAYS); + try { + Result<USERS> ru = service.getUsersByPermission(trans,type,instance,action); + switch(ru.status) { + case OK: + RosettaData<USERS> data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERS_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + + public static final String GET_HISTORY_USER = "getHistoryByUser"; + public static final String GET_HISTORY_ROLE = "getHistoryByRole"; + public static final String GET_HISTORY_PERM = "getHistoryByPerm"; + public static final String GET_HISTORY_NS = "getHistoryByNS"; + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getHistoryByUser(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result<Void> getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_USER); + sb.append(' '); + sb.append(user); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + + try { + Result<HISTORY> rh = service.getHistoryByUser(trans,user,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_USER); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getHistoryByRole(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) + */ + @Override + public Result<Void> getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String role, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_ROLE); + sb.append(' '); + sb.append(role); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + try { + Result<HISTORY> rh = service.getHistoryByRole(trans,role,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getHistoryByNS(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) + */ + @Override + public Result<Void> getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String ns, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_NS); + sb.append(' '); + sb.append(ns); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + try { + Result<HISTORY> rh = service.getHistoryByNS(trans,ns,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getHistoryByPerm(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) + */ + @Override + public Result<Void> getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String perm, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_PERM); + sb.append(' '); + sb.append(perm); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + try { + Result<HISTORY> rh = service.getHistoryByPerm(trans,perm,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_PERM); + return Result.err(e); + } finally { + tt.done(); + } + } + + public final static String CACHE_CLEAR = "cacheClear "; +// public final static String CACHE_VALIDATE = "validateCache"; + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String) + */ + @Override + public Result<Void> cacheClear(AuthzTrans trans, String cname) { + TimeTaken tt = trans.start(CACHE_CLEAR + cname, Env.SUB|Env.ALWAYS); + try { + return service.cacheClear(trans,cname); + } catch (Exception e) { + trans.error().log(e,IN,CACHE_CLEAR); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#cacheClear(org.onap.aaf.auth.env.test.AuthzTrans, java.lang.String, java.lang.Integer) + */ + @Override + public Result<Void> cacheClear(AuthzTrans trans, String cname, String segments) { + TimeTaken tt = trans.start(CACHE_CLEAR + cname + ", segments[" + segments + ']', Env.SUB|Env.ALWAYS); + try { + String[] segs = segments.split("\\s*,\\s*"); + int isegs[] = new int[segs.length]; + for(int i=0;i<segs.length;++i) { + try { + isegs[i] = Integer.parseInt(segs[i]); + } catch(NumberFormatException nfe) { + isegs[i] = -1; + } + } + return service.cacheClear(trans,cname, isegs); + } catch (Exception e) { + trans.error().log(e,IN,CACHE_CLEAR); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#dbReset(org.onap.aaf.auth.env.test.AuthzTrans) + */ + @Override + public void dbReset(AuthzTrans trans) { + service.dbReset(trans); + } + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getAPI(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse) + */ + public final static String API_REPORT = "apiReport"; + @Override + public Result<Void> getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet<AuthzTrans> rservlet) { + TimeTaken tt = trans.start(API_REPORT, Env.SUB); + try { + Api api = new Api(); + Api.Route ar; + Method[] meths = AuthzCassServiceImpl.class.getDeclaredMethods(); + for(RouteReport rr : rservlet.routeReport()) { + api.getRoute().add(ar = new Api.Route()); + ar.setMeth(rr.meth.name()); + ar.setPath(rr.path); + ar.setDesc(rr.desc); + ar.getContentType().addAll(rr.contextTypes); + for(Method m : meths) { + ApiDoc ad; + if((ad = m.getAnnotation(ApiDoc.class))!=null && + rr.meth.equals(ad.method()) && + rr.path.equals(ad.path())) { + for(String param : ad.params()) { + ar.getParam().add(param); + } + for(String text : ad.text()) { + ar.getComments().add(text); + } + ar.setExpected(ad.expectedCode()); + for(int ec : ad.errorCodes()) { + ar.getExplicitErr().add(ec); + } + } + } + } + RosettaData<Api> data = apiDF.newData(trans).load(api); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,apiDF.getOutType()); + return Result.ok(); + + } catch (Exception e) { + trans.error().log(e,IN,API_REPORT); + return Result.err(e); + } finally { + tt.done(); + } + } + + + public final static String API_EXAMPLE = "apiExample"; + + /* (non-Javadoc) + * @see com.att.authz.facade.AuthzFacade#getAPIExample(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result<Void> getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) { + TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB); + try { + String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional); + resp.getOutputStream().print(content); + setContentType(resp,content.contains("<?xml")?TYPE.XML:TYPE.JSON); + return Result.ok(); + } catch (Exception e) { + trans.error().log(e,IN,API_EXAMPLE); + return Result.err(Status.ERR_NotImplemented,e.getMessage()); + } finally { + tt.done(); + } + } + +}
\ No newline at end of file diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade_2_0.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade_2_0.java new file mode 100644 index 00000000..d6bbc378 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade_2_0.java @@ -0,0 +1,63 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.facade; + +import org.onap.aaf.auth.env.AuthzEnv; +import org.onap.aaf.auth.service.AuthzService; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Data; + +import aaf.v2_0.Approvals; +import aaf.v2_0.Certs; +import aaf.v2_0.Delgs; +import aaf.v2_0.Error; +import aaf.v2_0.History; +import aaf.v2_0.Keys; +import aaf.v2_0.Nss; +import aaf.v2_0.Perms; +import aaf.v2_0.Pkey; +import aaf.v2_0.Request; +import aaf.v2_0.Roles; +import aaf.v2_0.UserRoles; +import aaf.v2_0.Users; + +public class AuthzFacade_2_0 extends AuthzFacadeImpl< + Nss, + Perms, + Pkey, + Roles, + Users, + UserRoles, + Delgs, + Certs, + Keys, + Request, + History, + Error, + Approvals> +{ + public AuthzFacade_2_0(AuthzEnv env, + AuthzService<Nss, Perms, Pkey, Roles, Users, UserRoles, Delgs, Certs, Keys, Request, History, Error, Approvals> service, + Data.TYPE type) throws APIException { + super(env, service, type); + } +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper.java new file mode 100644 index 00000000..e7cedf96 --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper.java @@ -0,0 +1,123 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.mapper; + +import java.util.Collection; +import java.util.List; + +import org.onap.aaf.auth.dao.Bytification; +import org.onap.aaf.auth.dao.cass.ApprovalDAO; +import org.onap.aaf.auth.dao.cass.CertDAO; +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.dao.cass.DelegateDAO; +import org.onap.aaf.auth.dao.cass.FutureDAO; +import org.onap.aaf.auth.dao.cass.HistoryDAO; +import org.onap.aaf.auth.dao.cass.Namespace; +import org.onap.aaf.auth.dao.cass.PermDAO; +import org.onap.aaf.auth.dao.cass.RoleDAO; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.service.MayChange; +import org.onap.aaf.misc.rosetta.Marshal; + +public interface Mapper< + NSS, + PERMS, + PERMKEY, + ROLES, + USERS, + USERROLES, + DELGS, + CERTS, + KEYS, + REQUEST, + HISTORY, + ERROR, + APPROVALS> +{ + enum API{NSS,NS_REQ, + PERMS,PERM_KEY,PERM_REQ, + ROLES,ROLE,ROLE_REQ,ROLE_PERM_REQ, + USERS,USER_ROLE_REQ,USER_ROLES, + CRED_REQ,CERTS, + APPROVALS, + DELGS,DELG_REQ, + KEYS, + HISTORY, + ERROR, + API, + VOID}; + public Class<?> getClass(API api); + public<A> Marshal<A> getMarshal(API api); + public<A> A newInstance(API api); + + public Result<PermDAO.Data> permkey(AuthzTrans trans, PERMKEY from); + public Result<PermDAO.Data> perm(AuthzTrans trans, REQUEST from); + public Result<RoleDAO.Data> role(AuthzTrans trans, REQUEST from); + public Result<Namespace> ns(AuthzTrans trans, REQUEST from); + public Result<CredDAO.Data> cred(AuthzTrans trans, REQUEST from, boolean requiresPass); + public Result<USERS> cred(List<CredDAO.Data> lcred, USERS to); + public Result<CERTS> cert(List<CertDAO.Data> lcert, CERTS to); + public Result<DelegateDAO.Data> delegate(AuthzTrans trans, REQUEST from); + public Result<DELGS> delegate(List<DelegateDAO.Data> lDelg); + public Result<APPROVALS> approvals(List<ApprovalDAO.Data> lAppr); + public Result<List<ApprovalDAO.Data>> approvals(APPROVALS apprs); + public Result<List<PermDAO.Data>> perms(AuthzTrans trans, PERMS perms); + + public Result<UserRoleDAO.Data> userRole(AuthzTrans trans, REQUEST from); + public Result<PermDAO.Data> permFromRPRequest(AuthzTrans trans, REQUEST from); + public REQUEST ungrantRequest(AuthzTrans trans, String role, String type, String instance, String action); + public Result<RoleDAO.Data> roleFromRPRequest(AuthzTrans trans, REQUEST from); + + /* + * Check Requests of varying sorts for Future fields set + */ + public Result<FutureDAO.Data> future(AuthzTrans trans, String table, REQUEST from, Bytification content, boolean enableApproval, Memo memo, MayChange mc); + + public Result<NSS> nss(AuthzTrans trans, Namespace from, NSS to); + + // Note: Prevalidate if NS given is allowed to be seen before calling + public Result<NSS> nss(AuthzTrans trans, Collection<Namespace> from, NSS to); +// public Result<NSS> ns_attrib(AuthzTrans trans, Set<String> from, NSS to); + public Result<PERMS> perms(AuthzTrans trans, List<PermDAO.Data> from, PERMS to, boolean filter); + public Result<PERMS> perms(AuthzTrans trans, List<PermDAO.Data> from, PERMS to, String[] scopes, boolean filter); + public Result<ROLES> roles(AuthzTrans trans, List<RoleDAO.Data> from, ROLES roles, boolean filter); + // Note: Prevalidate if NS given is allowed to be seen before calling + public Result<USERS> users(AuthzTrans trans, Collection<UserRoleDAO.Data> from, USERS to); + public Result<USERROLES> userRoles(AuthzTrans trans, Collection<UserRoleDAO.Data> from, USERROLES to); + public Result<KEYS> keys(Collection<String> from); + + public Result<HISTORY> history(AuthzTrans trans, List<HistoryDAO.Data> history, final int sort); + + public ERROR errorFromMessage(StringBuilder holder, String msgID, String text, String... detail); + + /* + * A Memo Creator... Use to avoid creating superfluous Strings until needed. + */ + public static interface Memo { + public String get(); + } + + + +} diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java new file mode 100644 index 00000000..8b96172f --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java @@ -0,0 +1,875 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.mapper; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.UUID; + +import javax.xml.datatype.XMLGregorianCalendar; + +import org.onap.aaf.auth.dao.Bytification; +import org.onap.aaf.auth.dao.cass.ApprovalDAO; +import org.onap.aaf.auth.dao.cass.CertDAO; +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.dao.cass.DelegateDAO; +import org.onap.aaf.auth.dao.cass.FutureDAO; +import org.onap.aaf.auth.dao.cass.HistoryDAO; +import org.onap.aaf.auth.dao.cass.Namespace; +import org.onap.aaf.auth.dao.cass.NsSplit; +import org.onap.aaf.auth.dao.cass.NsType; +import org.onap.aaf.auth.dao.cass.PermDAO; +import org.onap.aaf.auth.dao.cass.RoleDAO; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.dao.cass.DelegateDAO.Data; +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.auth.dao.hl.Question.Access; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.env.AuthzTrans.REQD_TYPE; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.auth.org.Organization.Expiration; +import org.onap.aaf.auth.rserv.Pair; +import org.onap.aaf.auth.service.MayChange; +import org.onap.aaf.cadi.aaf.marshal.CertsMarshal; +import org.onap.aaf.cadi.util.Vars; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.util.Chrono; +import org.onap.aaf.misc.rosetta.Marshal; + +import aaf.v2_0.Api; +import aaf.v2_0.Approval; +import aaf.v2_0.Approvals; +import aaf.v2_0.Certs; +import aaf.v2_0.Certs.Cert; +import aaf.v2_0.CredRequest; +import aaf.v2_0.Delg; +import aaf.v2_0.DelgRequest; +import aaf.v2_0.Delgs; +import aaf.v2_0.Error; +import aaf.v2_0.History; +import aaf.v2_0.History.Item; +import aaf.v2_0.Keys; +import aaf.v2_0.NsRequest; +import aaf.v2_0.Nss; +import aaf.v2_0.Nss.Ns; +import aaf.v2_0.Perm; +import aaf.v2_0.PermKey; +import aaf.v2_0.PermRequest; +import aaf.v2_0.Perms; +import aaf.v2_0.Pkey; +import aaf.v2_0.Request; +import aaf.v2_0.Role; +import aaf.v2_0.RolePermRequest; +import aaf.v2_0.RoleRequest; +import aaf.v2_0.Roles; +import aaf.v2_0.UserRole; +import aaf.v2_0.UserRoleRequest; +import aaf.v2_0.UserRoles; +import aaf.v2_0.Users; +import aaf.v2_0.Users.User; + +public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRoles, Delgs, Certs, Keys, Request, History, Error, Approvals> { + private Question q; + + public Mapper_2_0(Question q) { + this.q = q; + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.mapper.Mapper#ns(java.lang.Object, org.onap.aaf.auth.service.mapper.Mapper.Holder) + */ + @Override + public Result<Namespace> ns(AuthzTrans trans, Request base) { + NsRequest from = (NsRequest)base; + Namespace namespace = new Namespace(); + namespace.name = from.getName(); + namespace.admin = from.getAdmin(); + namespace.owner = from.getResponsible(); + namespace.description = from.getDescription(); + trans.checkpoint(namespace.name, Env.ALWAYS); + + NsType nt = NsType.fromString(from.getType()); + if(nt.equals(NsType.UNKNOWN)) { + String ns = namespace.name; + int count = 0; + for(int i=ns.indexOf('.'); + i>=0; + i=ns.indexOf('.',i+1)) { + ++count; + } + switch(count) { + case 0: nt = NsType.ROOT;break; + case 1: nt = NsType.COMPANY;break; + default: nt = NsType.APP; + } + } + namespace.type = nt.type; + + return Result.ok(namespace); + } + + @Override + public Result<Nss> nss(AuthzTrans trans, Namespace from, Nss to) { + List<Ns> nss = to.getNs(); + Ns ns = new Ns(); + ns.setName(from.name); + if(from.admin!=null)ns.getAdmin().addAll(from.admin); + if(from.owner!=null)ns.getResponsible().addAll(from.owner); + if(from.attrib!=null) { + for(Pair<String,String> attrib : from.attrib) { + Ns.Attrib toAttrib = new Ns.Attrib(); + toAttrib.setKey(attrib.x); + toAttrib.setValue(attrib.y); + ns.getAttrib().add(toAttrib); + } + } + + ns.setDescription(from.description); + nss.add(ns); + return Result.ok(to); + } + + /** + * Note: Prevalidate if NS given is allowed to be seen before calling + */ + @Override + public Result<Nss> nss(AuthzTrans trans, Collection<Namespace> from, Nss to) { + List<Ns> nss = to.getNs(); + for(Namespace nd : from) { + Ns ns = new Ns(); + ns.setName(nd.name); + if(nd.admin!=null) { + ns.getAdmin().addAll(nd.admin); + } + if(nd.owner!=null) { + ns.getResponsible().addAll(nd.owner); + } + ns.setDescription(nd.description); + if(nd.attrib!=null) { + for(Pair<String,String> attrib : nd.attrib) { + Ns.Attrib toAttrib = new Ns.Attrib(); + toAttrib.setKey(attrib.x); + toAttrib.setValue(attrib.y); + ns.getAttrib().add(toAttrib); + } + } + + nss.add(ns); + } + return Result.ok(to); + } + + @Override + public Result<Perms> perms(AuthzTrans trans, List<PermDAO.Data> from, Perms to, boolean filter) { + List<Perm> perms = to.getPerm(); + final boolean addNS = trans.requested(REQD_TYPE.ns); + TimeTaken tt = trans.start("Filter Perms before return", Env.SUB); + try { + if(from!=null) { + for (PermDAO.Data data : from) { + if(!filter || q.mayUser(trans, trans.user(), data, Access.read).isOK()) { + Perm perm = new Perm(); + perm.setType(data.fullType()); + perm.setInstance(data.instance); + perm.setAction(data.action); + perm.setDescription(data.description); + if(addNS) { + perm.setNs(data.ns); + } + for(String role : data.roles(false)) { + perm.getRoles().add(role); + } + perms.add(perm); + } + } + } + } finally { + tt.done(); + } + + tt = trans.start("Sort Perms", Env.SUB); + try { + Collections.sort(perms, new Comparator<Perm>() { + @Override + public int compare(Perm perm1, Perm perm2) { + int typeCompare = perm1.getType().compareToIgnoreCase(perm2.getType()); + if (typeCompare == 0) { + int instanceCompare = perm1.getInstance().compareToIgnoreCase(perm2.getInstance()); + if (instanceCompare == 0) { + return perm1.getAction().compareToIgnoreCase(perm2.getAction()); + } + return instanceCompare; + } + return typeCompare; + } + }); + } finally { + tt.done(); + } + return Result.ok(to); + } + + @Override + public Result<Perms> perms(AuthzTrans trans, List<PermDAO.Data> from, Perms to, String[] nss, boolean filter) { + List<Perm> perms = to.getPerm(); + TimeTaken tt = trans.start("Filter Perms before return", Env.SUB); + try { + if(from!=null) { + boolean inNSS; + for (PermDAO.Data data : from) { + inNSS=false; + for(int i=0;!inNSS && i<nss.length;++i) { + if(nss[i].equals(data.ns)) { + inNSS=true; + } + } + if(inNSS && (!filter || q.mayUser(trans, trans.user(), data, Access.read).isOK())) { + Perm perm = new Perm(); + perm.setType(data.fullType()); + perm.setInstance(data.instance); + perm.setAction(data.action); + for(String role : data.roles(false)) { + perm.getRoles().add(role); + } + perm.setDescription(data.description); + perms.add(perm); + } + } + } + } finally { + tt.done(); + } + + tt = trans.start("Sort Perms", Env.SUB); + try { + Collections.sort(perms, new Comparator<Perm>() { + @Override + public int compare(Perm perm1, Perm perm2) { + int typeCompare = perm1.getType().compareToIgnoreCase(perm2.getType()); + if (typeCompare == 0) { + int instanceCompare = perm1.getInstance().compareToIgnoreCase(perm2.getInstance()); + if (instanceCompare == 0) { + return perm1.getAction().compareToIgnoreCase(perm2.getAction()); + } + return instanceCompare; + } + return typeCompare; + } + }); + } finally { + tt.done(); + } + return Result.ok(to); + } + + @Override + public Result<List<PermDAO.Data>> perms(AuthzTrans trans, Perms perms) { + List<PermDAO.Data> lpd = new ArrayList<PermDAO.Data>(); + for (Perm p : perms.getPerm()) { + Result<NsSplit> nss = q.deriveNsSplit(trans, p.getType()); + PermDAO.Data pd = new PermDAO.Data(); + if(nss.isOK()) { + pd.ns=nss.value.ns; + pd.type = nss.value.name; + pd.instance = p.getInstance(); + pd.action = p.getAction(); + for (String role : p.getRoles()) { + pd.roles(true).add(role); + } + lpd.add(pd); + } else { + return Result.err(nss); + } + } + return Result.ok(lpd); + } + + + @Override + public Result<PermDAO.Data> permkey(AuthzTrans trans, Pkey from) { + return q.permFrom(trans, from.getType(),from.getInstance(),from.getAction()); + } + + @Override + public Result<PermDAO.Data> permFromRPRequest(AuthzTrans trans, Request req) { + RolePermRequest from = (RolePermRequest)req; + Pkey perm = from.getPerm(); + if(perm==null)return Result.err(Status.ERR_NotFound, "Permission not found"); + Result<NsSplit> nss = q.deriveNsSplit(trans, perm.getType()); + PermDAO.Data pd = new PermDAO.Data(); + if(nss.isOK()) { + pd.ns=nss.value.ns; + pd.type = nss.value.name; + pd.instance = from.getPerm().getInstance(); + pd.action = from.getPerm().getAction(); + trans.checkpoint(pd.fullPerm(), Env.ALWAYS); + + String[] roles = {}; + + if (from.getRole() != null) { + roles = from.getRole().split(","); + } + for (String role : roles) { + pd.roles(true).add(role); + } + return Result.ok(pd); + } else { + return Result.err(nss); + } + } + + @Override + public Result<RoleDAO.Data> roleFromRPRequest(AuthzTrans trans, Request req) { + RolePermRequest from = (RolePermRequest)req; + Result<NsSplit> nss = q.deriveNsSplit(trans, from.getRole()); + RoleDAO.Data rd = new RoleDAO.Data(); + if(nss.isOK()) { + rd.ns = nss.value.ns; + rd.name = nss.value.name; + trans.checkpoint(rd.fullName(), Env.ALWAYS); + return Result.ok(rd); + } else { + return Result.err(nss); + } + } + + @Override + public Result<PermDAO.Data> perm(AuthzTrans trans, Request req) { + PermRequest from = (PermRequest)req; + Result<NsSplit> nss = q.deriveNsSplit(trans, from.getType()); + PermDAO.Data pd = new PermDAO.Data(); + if(nss.isOK()) { + pd.ns=nss.value.ns; + pd.type = nss.value.name; + pd.instance = from.getInstance(); + pd.action = from.getAction(); + pd.description = from.getDescription(); + trans.checkpoint(pd.fullPerm(), Env.ALWAYS); + return Result.ok(pd); + } else { + return Result.err(nss); + } + } + + @Override + public Request ungrantRequest(AuthzTrans trans, String role, String type, String instance, String action) { + RolePermRequest rpr = new RolePermRequest(); + Pkey pkey = new Pkey(); + pkey.setType(type); + pkey.setInstance(instance); + pkey.setAction(action); + rpr.setPerm(pkey); + + rpr.setRole(role); + return rpr; + } + + @Override + public Result<RoleDAO.Data> role(AuthzTrans trans, Request base) { + RoleRequest from = (RoleRequest)base; + Result<NsSplit> nss = q.deriveNsSplit(trans, from.getName()); + if(nss.isOK()) { + RoleDAO.Data to = new RoleDAO.Data(); + to.ns = nss.value.ns; + to.name = nss.value.name; + to.description = from.getDescription(); + trans.checkpoint(to.fullName(), Env.ALWAYS); + + return Result.ok(to); + } else { + return Result.err(nss); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.mapper.Mapper#roles(java.util.List) + */ + @Override + public Result<Roles> roles(AuthzTrans trans, List<RoleDAO.Data> from, Roles to, boolean filter) { + final boolean needNS = trans.requested(REQD_TYPE.ns); + for(RoleDAO.Data frole : from) { + // Only Add Data to view if User is allowed to see this Role + //if(!filter || q.mayUserViewRole(trans, trans.user(), frole).isOK()) { + if(!filter || q.mayUser(trans, trans.user(), frole,Access.read).isOK()) { + Role role = new Role(); + role.setName(frole.ns + '.' + frole.name); + role.setDescription(frole.description); + if(needNS) { + role.setNs(frole.ns); + } + for(String p : frole.perms(false)) { // can see any Perms in the Role he has permission for + Result<String[]> rpa = PermDAO.Data.decodeToArray(trans,q,p); + if(rpa.notOK()) return Result.err(rpa); + + String[] pa = rpa.value; + Pkey pKey = new Pkey(); + pKey.setType(pa[0]+'.'+pa[1]); + pKey.setInstance(pa[2]); + pKey.setAction(pa[3]); + role.getPerms().add(pKey); + } + to.getRole().add(role); + } + } + return Result.ok(to); + } + + /* + * (non-Javadoc) + * @see org.onap.aaf.auth.service.mapper.Mapper#users(java.util.Collection, java.lang.Object) + * + * Note: Prevalidate all data for permission to view + */ + @Override + public Result<Users> users(AuthzTrans trans, Collection<UserRoleDAO.Data> from, Users to) { + List<User> cu = to.getUser(); + for(UserRoleDAO.Data urd : from) { + User user = new User(); + user.setId(urd.user); + if(urd.expires!=null) { + user.setExpires(Chrono.timeStamp(urd.expires)); + } + cu.add(user); + } + return Result.ok(to); + } + + /* + * (non-Javadoc) + * @see org.onap.aaf.auth.service.mapper.Mapper#users(java.util.Collection, java.lang.Object) + * + * Note: Prevalidate all data for permission to view + */ + @Override + public Result<UserRoles> userRoles(AuthzTrans trans, Collection<UserRoleDAO.Data> from, UserRoles to) { + List<UserRole> cu = to.getUserRole(); + for(UserRoleDAO.Data urd : from) { + UserRole ur = new UserRole(); + ur.setUser(urd.user); + ur.setRole(urd.role); + ur.setExpires(Chrono.timeStamp(urd.expires)); + cu.add(ur); + } + return Result.ok(to); + } + + /** + * + * @param base + * @param start + * @return + */ + @Override + public Result<UserRoleDAO.Data> userRole(AuthzTrans trans, Request base) { + try { + UserRoleRequest from = (UserRoleRequest)base; + + // Setup UserRoleData, either for immediate placement, or for futureIt i + UserRoleDAO.Data to = new UserRoleDAO.Data(); + if (from.getUser() != null) { + String user = from.getUser(); + to.user = user; + } + if (from.getRole() != null) { + to.role(trans,q,from.getRole()); + } + to.expires = getExpires(trans.org(),Expiration.UserInRole,base,from.getUser()); + trans.checkpoint(to.toString(), Env.ALWAYS); + + return Result.ok(to); + } catch (Exception t) { + return Result.err(Status.ERR_BadData,t.getMessage()); + } + } + + @Override + public Result<CredDAO.Data> cred(AuthzTrans trans, Request base, boolean requiresPass) { + CredRequest from = (CredRequest)base; + CredDAO.Data to = new CredDAO.Data(); + to.id=from.getId(); + to.ns = Question.domain2ns(to.id); + String passwd = from.getPassword(); + if(requiresPass) { + String ok = trans.org().isValidPassword(trans, to.id,passwd); + if(ok.length()>0) { + return Result.err(Status.ERR_BadData,ok); + } + + } else { + to.type=0; + } + if(passwd != null) { + to.cred = ByteBuffer.wrap(passwd.getBytes()); + to.type = CredDAO.RAW; + } else { + to.type = 0; + } + + // Note: Ensure requested EndDate created will match Organization Password Rules + // P.S. Do not apply TempPassword rule here. Do that when you know you are doing a Create/Reset (see Service) + to.expires = getExpires(trans.org(),Expiration.Password,base,from.getId()); + trans.checkpoint(to.id, Env.ALWAYS); + + return Result.ok(to); + } + + @Override + public Result<Users> cred(List<CredDAO.Data> from, Users to) { + List<User> cu = to.getUser(); + for(CredDAO.Data cred : from) { + User user = new User(); + user.setId(cred.id); + user.setExpires(Chrono.timeStamp(cred.expires)); + user.setType(cred.type); + cu.add(user); + } + return Result.ok(to); + } + + @Override + public Result<Certs> cert(List<CertDAO.Data> from, Certs to) { + List<Cert> lc = to.getCert(); + for(CertDAO.Data fcred : from) { + Cert cert = new Cert(); + cert.setId(fcred.id); + cert.setX500(fcred.x500); + /**TODO - change Interface + * @deprecated */ + cert.setFingerprint(fcred.serial.toByteArray()); + lc.add(cert); + } + return Result.ok(to); + } + + /** + * Analyze whether Requests should be acted on now, or in the future, based on Start Date, and whether the requester + * is allowed to change this value directly + * + * Returning Result.OK means it should be done in the future. + * Returning Result.ACC_Now means to act on table change now. + */ + @Override + public Result<FutureDAO.Data> future(AuthzTrans trans, String table, Request from, + Bytification content, boolean enableApproval, Memo memo, MayChange mc) { + Result<?> rMayChange; + boolean needsAppr = enableApproval?trans.requested(REQD_TYPE.future):false; + if(!needsAppr && (needsAppr = (rMayChange=mc.mayChange()).notOK())) { + if(enableApproval) { + if(!trans.requested(AuthzTrans.REQD_TYPE.future)) { + return Result.err(rMayChange); + } + } else { + return Result.err(rMayChange); + } + } + GregorianCalendar now = new GregorianCalendar(); + GregorianCalendar start = from.getStart()==null?now:from.getStart().toGregorianCalendar(); + + GregorianCalendar expires = trans.org().expiration(start, Expiration.Future); + XMLGregorianCalendar xgc; + if((xgc=from.getEnd())!=null) { + GregorianCalendar fgc = xgc.toGregorianCalendar(); + expires = expires.before(fgc)?expires:fgc; // Min of desired expiration, and Org expiration + } + + //TODO needs two answers from this. What's the NSS, and may Change. + FutureDAO.Data fto; + if(start.after(now) || needsAppr ) { + //String user = trans.user(); + fto = new FutureDAO.Data(); + fto.target=table; + fto.memo = memo.get(); + fto.start = start.getTime(); + fto.expires = expires.getTime(); + if(needsAppr) { // Need to add Approvers... + /* + Result<Data> rslt = mc.getNsd(); + if(rslt.notOKorIsEmpty())return Result.err(rslt); + appr.addAll(mc.getNsd().value.responsible); + try { + //Note from 2013 Is this getting Approvers for user only? What about Delegates? + // 3/25/2014. Approvers are set by Corporate policy. We don't have to worry here about what that means. + // It is important to get Delegates, if necessary, at notification time + // If we add delegates now, it will get all confused as to who is actually responsible. + for(Organization.User ou : org.getApprovers(trans, user)) { + appr.add(ou.email); + } + } catch (Exception e) { + return Result.err(Status.ERR_Policy,org.getName() + " did not respond with Approvers: " + e.getLocalizedMessage()); + } + */ + } + try { + fto.construct = content.bytify(); + } catch (Exception e) { + return Result.err(Status.ERR_BadData,"Data cannot be saved for Future."); + } + } else { + return Result.err(Status.ACC_Now, "Make Data changes now."); + } + return Result.ok(fto); + } + + + /* (non-Javadoc) + * @see org.onap.aaf.auth.service.mapper.Mapper#history(java.util.List) + */ + @Override + public Result<History> history(AuthzTrans trans, List<HistoryDAO.Data> history, final int sort) { + History hist = new History(); + List<Item> items = hist.getItem(); + for(HistoryDAO.Data data : history) { + History.Item item = new History.Item(); + item.setYYYYMM(Integer.toString(data.yr_mon)); + Date date = Chrono.uuidToDate(data.id); + item.setTimestamp(Chrono.timeStamp(date)); + item.setAction(data.action); + item.setMemo(data.memo); + item.setSubject(data.subject); + item.setTarget(data.target); + item.setUser(data.user); + items.add(item); + } + + if(sort != 0) { + TimeTaken tt = trans.start("Sort ", Env.SUB); + try { + java.util.Collections.sort(items, new Comparator<Item>() { + @Override + public int compare(Item o1, Item o2) { + return sort*(o1.getTimestamp().compare(o2.getTimestamp())); + } + }); + } finally { + tt.done(); + } + } + return Result.ok(hist); + } + + @Override + public Error errorFromMessage(StringBuilder holder, String msgID, String text, String... var) { + Error err = new Error(); + err.setMessageId(msgID); + // AT&T Restful Error Format requires numbers "%" placements + err.setText(Vars.convert(holder, text, var)); + for(String s : var) { + err.getVariables().add(s); + } + return err; + } + + @Override + public Class<?> getClass(API api) { + switch(api) { + case NSS: return Nss.class; + case NS_REQ: return NsRequest.class; + case PERMS: return Perms.class; + case PERM_KEY: return PermKey.class; + case ROLES: return Roles.class; + case ROLE: return Role.class; + case USERS: return Users.class; + case DELGS: return Delgs.class; + case CERTS: return Certs.class; + case DELG_REQ: return DelgRequest.class; + case PERM_REQ: return PermRequest.class; + case ROLE_REQ: return RoleRequest.class; + case CRED_REQ: return CredRequest.class; + case USER_ROLE_REQ: return UserRoleRequest.class; + case USER_ROLES: return UserRoles.class; + case ROLE_PERM_REQ: return RolePermRequest.class; + case APPROVALS: return Approvals.class; + case KEYS: return Keys.class; + case HISTORY: return History.class; +// case MODEL: return Model.class; + case ERROR: return Error.class; + case API: return Api.class; + case VOID: return Void.class; + } + return null; + } + + @SuppressWarnings("unchecked") + @Override + public <A> A newInstance(API api) { + switch(api) { + case NS_REQ: return (A) new NsRequest(); + case NSS: return (A) new Nss(); + case PERMS: return (A)new Perms(); + case PERM_KEY: return (A)new PermKey(); + case ROLES: return (A)new Roles(); + case ROLE: return (A)new Role(); + case USERS: return (A)new Users(); + case DELGS: return (A)new Delgs(); + case CERTS: return (A)new Certs(); + case PERM_REQ: return (A)new PermRequest(); + case CRED_REQ: return (A)new CredRequest(); + case ROLE_REQ: return (A)new RoleRequest(); + case USER_ROLE_REQ: return (A)new UserRoleRequest(); + case USER_ROLES: return (A)new UserRoles(); + case ROLE_PERM_REQ: return (A)new RolePermRequest(); + case HISTORY: return (A)new History(); + case KEYS: return (A)new Keys(); + //case MODEL: return (A)new Model(); + case ERROR: return (A)new Error(); + case API: return (A)new Api(); + case VOID: return null; + + case APPROVALS: return (A) new Approvals(); + case DELG_REQ: return (A) new DelgRequest(); + } + return null; + } + + @SuppressWarnings("unchecked") + /** + * Get Typed Marshaler as they are defined + * + * @param api + * @return + */ + public <A> Marshal<A> getMarshal(API api) { + switch(api) { + case CERTS: return (Marshal<A>) new CertsMarshal(); + default: + return null; + } + } + + @Override + public Result<Approvals> approvals(List<ApprovalDAO.Data> lAppr) { + Approvals apprs = new Approvals(); + List<Approval> lappr = apprs.getApprovals(); + Approval a; + for(ApprovalDAO.Data appr : lAppr) { + a = new Approval(); + a.setId(appr.id.toString()); + if(appr.ticket==null) { + a.setTicket(null); + } else { + a.setTicket(appr.ticket.toString()); + } + a.setUser(appr.user); + a.setApprover(appr.approver); + a.setType(appr.type); + a.setStatus(appr.status); + a.setMemo(appr.memo); + a.setOperation(appr.operation); + a.setUpdated(Chrono.timeStamp(appr.updated)); + lappr.add(a); + } + return Result.ok(apprs); + } + + @Override + public Result<List<ApprovalDAO.Data>> approvals(Approvals apprs) { + List<ApprovalDAO.Data> lappr = new ArrayList<ApprovalDAO.Data>(); + for(Approval a : apprs.getApprovals()) { + ApprovalDAO.Data ad = new ApprovalDAO.Data(); + String str = a.getId(); + if(str!=null)ad.id=UUID.fromString(str); + str = a.getTicket(); + if(str!=null)ad.ticket=UUID.fromString(str); + ad.user=a.getUser(); + ad.approver=a.getApprover(); + ad.type=a.getType(); + ad.status=a.getStatus(); + ad.operation=a.getOperation(); + ad.memo=a.getMemo(); + + XMLGregorianCalendar xgc = a.getUpdated(); + if(xgc!=null)ad.updated=xgc.toGregorianCalendar().getTime(); + lappr.add(ad); + } + return Result.ok(lappr); + } + + @Override + public Result<Delgs> delegate(List<DelegateDAO.Data> lDelg) { + Delgs delgs = new Delgs(); + List<Delg> ldelg = delgs.getDelgs(); + Delg d; + for(DelegateDAO.Data del: lDelg) { + d = new Delg(); + d.setUser(del.user); + d.setDelegate(del.delegate); + if(del.expires!=null)d.setExpires(Chrono.timeStamp(del.expires)); + ldelg.add(d); + } + return Result.ok(delgs); + } + + @Override + public Result<Data> delegate(AuthzTrans trans, Request base) { + try { + DelgRequest from = (DelgRequest)base; + DelegateDAO.Data to = new DelegateDAO.Data(); + String user = from.getUser(); + to.user = user; + String delegate = from.getDelegate(); + to.delegate = delegate; + to.expires = getExpires(trans.org(),Expiration.UserDelegate,base,from.getUser()); + trans.checkpoint(to.user+"=>"+to.delegate, Env.ALWAYS); + + return Result.ok(to); + } catch (Exception t) { + return Result.err(Status.ERR_BadData,t.getMessage()); + } + } + + /* + * We want "Expired" dates to start at a specified time set by the Organization, and consistent wherever + * the date is created from. + */ + private Date getExpires(Organization org, Expiration exp, Request base, String id) { + XMLGregorianCalendar end = base.getEnd(); + GregorianCalendar gc = end==null?new GregorianCalendar():end.toGregorianCalendar(); + GregorianCalendar orggc; + orggc = org.expiration(gc,exp,id); + + // We'll choose the lesser of dates to ensure Policy Compliance... + + GregorianCalendar endgc = end==null||gc.after(orggc)?orggc:gc; + // Allow the Organization to determine when official "day Start" begins, Specifically when to consider something Expired. + endgc = Chrono.firstMomentOfDay(endgc); + endgc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay()); + return endgc.getTime(); + } + + + @Override + public Result<Keys> keys(Collection<String> from) { + Keys keys = new Keys(); + keys.getKey().addAll(from); + return Result.ok(keys).emptyList(from.isEmpty()); + } + +}
\ No newline at end of file diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java new file mode 100644 index 00000000..446bf46d --- /dev/null +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java @@ -0,0 +1,253 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.service.validation; + +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.dao.cass.DelegateDAO; +import org.onap.aaf.auth.dao.cass.Namespace; +import org.onap.aaf.auth.dao.cass.PermDAO; +import org.onap.aaf.auth.dao.cass.RoleDAO; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.auth.rserv.Pair; +import org.onap.aaf.auth.validation.Validator; + +/** + * Validator + * Consistently apply content rules for content (incoming) + * + * Note: We restrict content for usability in URLs (because RESTful service), and avoid + * issues with Regular Expressions, and other enabling technologies. + * @author Jonathan + * + */ +public class ServiceValidator extends Validator { + public ServiceValidator perm(Result<PermDAO.Data> rpd) { + if(rpd.notOK()) { + msg(rpd.details); + } else { + perm(rpd.value); + } + return this; + } + + + public ServiceValidator perm(PermDAO.Data pd) { + if(pd==null) { + msg("Perm Data is null."); + } else { + ns(pd.ns); + permType(pd.type,pd.ns); + permInstance(pd.instance); + permAction(pd.action); + if(pd.roles!=null) { + for(String role : pd.roles) { + role(role); + } + } + if(pd.roles!=null) { + for(String r : pd.roles) { + role(r); + } + } + description("Perm",pd.description); + } + return this; + } + + public ServiceValidator role(Result<RoleDAO.Data> rrd) { + if(rrd.notOK()) { + msg(rrd.details); + } else { + role(rrd.value); + } + return this; + } + + public ServiceValidator role(RoleDAO.Data pd) { + if(pd==null) { + msg("Role Data is null."); + } else { + ns(pd.ns); + role(pd.name); + if(pd.perms!=null) { + for(String perm : pd.perms) { + String[] ps = perm.split("\\|"); + if(ps.length!=3) { + msg("Perm [" + perm + "] in Role [" + pd.fullName() + "] is not correctly separated with '|'"); + } else { + permType(ps[0],null); + permInstance(ps[1]); + permAction(ps[2]); + } + } + } + description("Role",pd.description); + } + return this; + } + + public ServiceValidator delegate(Organization org, Result<DelegateDAO.Data> rdd) { + if(rdd.notOK()) { + msg(rdd.details); + } else { + delegate(org, rdd.value); + } + return this; + } + + public ServiceValidator delegate(Organization org, DelegateDAO.Data dd) { + if(dd==null) { + msg("Delegate Data is null."); + } else { + user(org,dd.user); + user(org,dd.delegate); + } + return this; + } + + + public ServiceValidator cred(AuthzTrans trans, Organization org, Result<CredDAO.Data> rcd, boolean isNew) { + if(rcd.notOK()) { + msg(rcd.details); + } else { + cred(trans, org,rcd.value,isNew); + } + return this; + } + + public ServiceValidator cred(AuthzTrans trans, Organization org, CredDAO.Data cd, boolean isNew) { + if(cd==null) { + msg("Cred Data is null."); + } else { + if(nob(cd.id,ID_CHARS)) { + msg("ID [" + cd.id + "] is invalid in " + org.getName()); + } + if(!org.isValidCred(trans, cd.id)) { + msg("ID [" + cd.id + "] is invalid for a cred in " + org.getName()); + } + String str = cd.id; + int idx = str.indexOf('@'); + if(idx>0) { + str = str.substring(0,idx); + } + + if(cd.id.endsWith(org.getRealm())) { + if(isNew && (str=org.isValidID(trans, str)).length()>0) { + msg(cd.id,str); + } + } + + if(cd.type==null) { + msg("Credential Type must be set"); + } else { + switch(cd.type) { + case CredDAO.BASIC_AUTH_SHA256: + // ok + break; + default: + msg("Credential Type [",Integer.toString(cd.type),"] is invalid"); + } + } + } + return this; + } + + + public ServiceValidator user(Organization org, String user) { + if(nob(user,ID_CHARS)) { + msg("User [",user,"] is invalid."); + } + return this; + } + + public ServiceValidator ns(Result<Namespace> nsd) { + notOK(nsd); + ns(nsd.value); + return this; + } + + public ServiceValidator ns(Namespace ns) { + ns(ns.name); + for(String s : ns.admin) { + if(nob(s,ID_CHARS)) { + msg("Admin [" + s + "] is invalid."); + } + + } + for(String s : ns.owner) { + if(nob(s,ID_CHARS)) { + msg("Responsible [" + s + "] is invalid."); + } + + } + + if(ns.attrib!=null) { + for(Pair<String, String> at : ns.attrib) { + if(nob(at.x,NAME_CHARS)) { + msg("Attribute tag [" + at.x + "] is invalid."); + } + if(nob(at.x,NAME_CHARS)) { + msg("Attribute value [" + at.y + "] is invalid."); + } + } + } + + description("Namespace",ns.description); + return this; + } + + public ServiceValidator user_role(UserRoleDAO.Data urdd) { + if(urdd==null) { + msg("UserRole is null"); + } else { + role(urdd.role); + nullOrBlank("UserRole.ns",urdd.ns); + nullOrBlank("UserRole.rname",urdd.rname); + } + return this; + } + + public ServiceValidator nullOrBlank(PermDAO.Data pd) { + if(pd==null) { + msg("Permission is null"); + } else { + nullOrBlank("NS",pd.ns). + nullOrBlank("Type",pd.type). + nullOrBlank("Instance",pd.instance). + nullOrBlank("Action",pd.action); + } + return this; + } + + public ServiceValidator nullOrBlank(RoleDAO.Data rd) { + if(rd==null) { + msg("Role is null"); + } else { + nullOrBlank("NS",rd.ns). + nullOrBlank("Name",rd.name); + } + return this; + } +} diff --git a/auth/auth-service/src/main/resources/docker-compose/.gitignore b/auth/auth-service/src/main/resources/docker-compose/.gitignore new file mode 100644 index 00000000..fc7349f7 --- /dev/null +++ b/auth/auth-service/src/main/resources/docker-compose/.gitignore @@ -0,0 +1,2 @@ +/docker-compose.yml +/startupaaf.sh diff --git a/auth/auth-service/src/main/resources/docker-compose/data/.gitignore b/auth/auth-service/src/main/resources/docker-compose/data/.gitignore new file mode 100644 index 00000000..41ab7536 --- /dev/null +++ b/auth/auth-service/src/main/resources/docker-compose/data/.gitignore @@ -0,0 +1,2 @@ +/identities.dat +/identities.idx diff --git a/auth/auth-service/src/main/resources/docker-compose/data/ecomp.cql b/auth/auth-service/src/main/resources/docker-compose/data/ecomp.cql new file mode 100644 index 00000000..6fddf650 --- /dev/null +++ b/auth/auth-service/src/main/resources/docker-compose/data/ecomp.cql @@ -0,0 +1,169 @@ +USE authz; + +// Create Root pass +INSERT INTO cred (id,ns,type,cred,expires) + VALUES ('dgl@openecomp.org','org.openecomp',1,0xab3831f27b39d7a039f9a92aa2bbfe51,'2020-12-31'); + +INSERT INTO cred (id,ns,type,cred,expires) + VALUES ('m99751@dmaapBC.openecomp.org','org.openecomp.dmaapBC',1,0xab3831f27b39d7a039f9a92aa2bbfe51,'2020-12-31'); + +INSERT INTO cred (id,ns,type,cred,expires) + VALUES ('m99501@dmaapBC.openecomp.org','org.openecomp.dmaapBC',1,0xab3831f27b39d7a039f9a92aa2bbfe51,'2020-12-31'); + + +// Create 'com' root NS +INSERT INTO ns (name,scope,description,parent,type) + VALUES('com',1,'Root Namespace',null,1); + +INSERT INTO role(ns, name, perms, description) + VALUES('com','admin',{'com.access|*|*'},'Com Admins'); + +INSERT INTO role(ns, name, perms, description) + VALUES('com','owner',{'com.access|*|read'},'Com Owners'); + +INSERT INTO perm(ns, type, instance, action, roles, description) + VALUES ('com','access','*','read',{'com.owner'},'Com Read Access'); + +INSERT INTO perm(ns, type, instance, action, roles, description) + VALUES ('com','access','*','*',{'com.admin'},'Com Write Access'); + +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','com.owner','2020-12-31','com','owner'); + +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','com.admin','2020-12-31','com','admin'); + +// Create org root NS +INSERT INTO ns (name,scope,description,parent,type) + VALUES('org',1,'Root Namespace Org',null,1); + +INSERT INTO ns (name,scope,description,parent,type) + VALUES('org.openecomp.dcae',3,'DCAE Namespace Org','org.openecomp',3); + +INSERT INTO ns (name,scope,description,parent,type) + VALUES('org.openecomp.dmaapBC',3,'DMaaP BC Namespace Org','org.openecomp',3); + +INSERT INTO role(ns, name, perms, description) + VALUES('org','admin',{'org.access|*|*'},'Com Admins'); + +INSERT INTO role(ns, name, perms, description) + VALUES('org','owner',{'org.access|*|read'},'Com Owners'); + +INSERT INTO perm(ns, type, instance, action, roles, description) + VALUES ('org','access','*','read',{'org.owner'},'Com Read Access'); + +INSERT INTO perm(ns, type, instance, action, roles, description) + VALUES ('org','access','*','*',{'org.admin'},'Com Write Access'); + +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','org.owner','2020-12-31','org','owner'); + +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','org.admin','2020-12-31','org','admin'); + + +// Create com.att + +INSERT INTO ns (name,scope,description,parent,type) + VALUES('com.att',2,'AT&T Namespace','com',2); + +INSERT INTO role(ns, name, perms,description) + VALUES('com.att','admin',{'com.att.access|*|*'},'AT&T Admins'); + +INSERT INTO role(ns, name, perms,description) + VALUES('com.att','owner',{'com.att.access|*|read'},'AT&T Owners'); + +INSERT INTO perm(ns, type, instance, action, roles,description) + VALUES ('com.att','access','*','read',{'com.att.owner'},'AT&T Read Access'); + +INSERT INTO perm(ns, type, instance, action, roles,description) + VALUES ('com.att','access','*','*',{'com.att.admin'},'AT&T Write Access'); + +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','com.att.owner','2020-12-31','com.att','owner'); + +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','com.att.admin','2020-12-31','com.att','admin'); + +// Create com.att.aaf + +INSERT INTO ns (name,scope,description,parent,type) + VALUES('com.att.aaf',3,'Application Authorization Framework','com.att',3); + +INSERT INTO role(ns, name, perms, description) + VALUES('com.att.aaf','admin',{'com.att.aaf.access|*|*'},'AAF Admins'); + +INSERT INTO role(ns, name, perms, description) + VALUES('com.att.aaf','owner',{'com.att.aaf.access|*|read'},'AAF Owners'); + +INSERT INTO perm(ns, type, instance, action, roles, description) + VALUES ('com.att.aaf','access','*','read',{'com.att.aaf.owner'},'AAF Read Access'); + +INSERT INTO perm(ns, type, instance, action, roles, description) + VALUES ('com.att.aaf','access','*','*',{'com.att.aaf.admin'},'AAF Write Access'); + +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','com.att.aaf.admin','2020-12-31','com.att.aaf','admin'); +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','com.att.aaf.owner','2020-12-31','com.att.aaf','owner'); + + +// Create org.openecomp +INSERT INTO ns (name,scope,description,parent,type) + VALUES('org.openecomp',2,'Open EComp NS','com.att',2); + +INSERT INTO role(ns, name, perms, description) + VALUES('org.openecomp','admin',{'org.openecomp.access|*|*'},'OpenEcomp Admins'); + +INSERT INTO role(ns, name, perms, description) + VALUES('org.openecomp','owner',{'org.openecomp.access|*|read'},'OpenEcomp Owners'); + +INSERT INTO perm(ns, type, instance, action, roles, description) + VALUES ('org.openecomp','access','*','read',{'org.openecomp.owner'},'OpenEcomp Read Access'); + +INSERT INTO perm(ns, type, instance, action, roles, description) + VALUES ('org.openecomp','access','*','*',{'org.openecomp.admin'},'OpenEcomp Write Access'); + +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','org.openecomp.admin','2020-12-31','org.openecomp','admin'); + +// Create org.openecomp.dmaapBC + +INSERT INTO ns (name,scope,description,parent,type) + VALUES('org.openecomp.dmaapBC',3,'Application Authorization Framework','org.openecomp',3); + +//INSERT INTO role(ns, name, perms, description) +// VALUES('org.openecomp.dmaapBC','admin',{'org.openecomp.dmaapBC.access|*|*'},'AAF Admins'); + +INSERT INTO role(ns, name, perms, description) +VALUES('org.openecomp.dmaapBC','admin',{'org.openecomp.dmaapBC.access|*|*','org.openecomp.dmaapBC.topicFactory|:org.openecomp.dmaapBC.topic:org.openecomp.dmaapBC|create','org.openecomp.dmaapBC.mr.topic|:topic.org.openecomp.dmaapBC.newtopic|sub','org.openecomp.dmaapBC.mr.topic|:topic.org.openecomp.dmaapBC.newtopic|pub'},'AAF Admins'); + +//INSERT INTO role(ns, name, perms, description) +//VALUES('org.openecomp.dmaapBC','admin',{'org.openecomp.dmaapBC.access|*|*','org.openecomp.dmaapBC.mr.topic|:topic.org.openecomp.dmaapBC.newtopic|sub'},'AAF Admins'); + +//INSERT INTO role(ns, name, perms, description) +//VALUES('org.openecomp.dmaapBC','admin',{'org.openecomp.dmaapBC.access|*|*','org.openecomp.dmaapBC.mr.topic|:topic.org.openecomp.dmaapBC.newtopic|pub'},'AAF Admins'); + + + +INSERT INTO role(ns, name, perms, description) + VALUES('org.openecomp.dmaapBC','owner',{'org.openecomp.dmaapBC.access|*|read'},'AAF Owners'); + +INSERT INTO perm(ns, type, instance, action, roles, description) + VALUES ('org.openecomp.dmaapBC','access','*','read',{'org.openecomp.dmaapBC.owner'},'AAF Read Access'); + +INSERT INTO perm(ns, type, instance, action, roles, description) + VALUES ('org.openecomp.dmaapBC','access','*','*',{'org.openecomp.dmaapBC.admin'},'AAF Write Access'); + +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','org.openecomp.dmaapBC.admin','2020-12-31','org.openecomp.dmaapBC','admin'); +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('dgl@openecomp.org','org.openecomp.dmaapBC.owner','2020-12-31','org.openecomp.dmaapBC','owner'); +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('m99751@dmaapBC.openecomp.org','org.openecomp.dmaapBC.admin','2020-12-31','org.openecomp.dmaapBC','admin'); +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('m99751@dmaapBC.openecomp.org','org.openecomp.dmaapBC.owner','2020-12-31','org.openecomp.dmaapBC','owner'); +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('m99501@dmaapBC.openecomp.org','org.openecomp.dmaapBC.admin','2020-12-31','org.openecomp.dmaapBC','admin'); +INSERT INTO user_role(user,role,expires,ns,rname) + VALUES ('m99501@dmaapBC.openecomp.org','org.openecomp.dmaapBC.owner','2020-12-31','org.openecomp.dmaapBC','owner'); diff --git a/auth/auth-service/src/main/resources/docker-compose/data/init.cql b/auth/auth-service/src/main/resources/docker-compose/data/init.cql new file mode 100644 index 00000000..81700f83 --- /dev/null +++ b/auth/auth-service/src/main/resources/docker-compose/data/init.cql @@ -0,0 +1,242 @@ +// For Developer Machine single instance +// +CREATE KEYSPACE authz +WITH REPLICATION = {'class' : 'SimpleStrategy','replication_factor':1}; +// +// From Ravi, 6-17-2014. User for DEVL->TEST +// +// CREATE KEYSPACE authz WITH replication = { 'class': 'NetworkTopologyStrategy', 'HYWRCA02': '2', 'BRHMALDC': '2' }; +// +// PROD +// +// CREATE KEYSPACE authz WITH replication = {'class': 'NetworkTopologyStrategy','ALPSGACT': '2','STLSMORC': '2','BRHMALDC': '2' }; +// +// create user authz with password '<AUTHZ PASSWORD>' superuser; +// grant all on keyspace authz to authz; +// +// For TEST (aaf_test) +// CREATE KEYSPACE authz WITH replication = { 'class': 'NetworkTopologyStrategy', 'BRHMALDC': '1' }; +// +// DEVL +// CREATE KEYSPACE authz WITH replication = {'class': 'NetworkTopologyStrategy','STLSMORC': '2' }; +// +// TEST / PERF +// CREATE KEYSPACE authz WITH replication = {'class': 'NetworkTopologyStrategy','STLSMORC': '3','KGMTNC20': '3' }; +// +// IST +// CREATE KEYSPACE authz WITH replication = {'class': 'NetworkTopologyStrategy','STLSMORC':'3', +// 'DLLSTXCF':'3','KGMTNC20':'3','SFLDMIBB':'3','HYWRCA02':'3' }; +// +// with 6 localized with ccm +// CREATE KEYSPACE authz WITH replication = { 'class': 'NetworkTopologyStrategy', 'dc1': '2', 'dc2': '2' }; +// + +USE authz; + +// +// CORE Table function +// + +// Namespace - establish hierarchical authority to modify +// Permissions and Roles +// "scope" is flag to determine Policy. Typical important scope +// is "company" (1) +CREATE TABLE ns ( + name varchar, + scope int, // deprecated 2.0.11 + description varchar, + parent varchar, + type int, + PRIMARY KEY (name) +); +CREATE INDEX ns_parent on ns(parent); + + +// Oct 2015, not performant. Made Owner and Attrib first class Roles, +// April, 2015. Originally, the plan was to utilize Cassandra 2.1.2, however, other team's preferences were to remain at current levels. +// Therefore, we are taking the separate table approach. (coder Jeremiah Rohwedder) +// We had dropped this by making first class objects of Responsible (Owner) and Admin. We need this again to mark namespaces +// as having certain tools, like SWM, etc. +CREATE TABLE ns_attrib ( + ns varchar, + key varchar, + value varchar, + PRIMARY KEY (ns,key) +); +create index ns_attrib_key on ns_attrib(key); + +// Will be cached +CREATE TABLE role ( + ns varchar, + name varchar, + perms set<varchar>, // Use "Key" of "name|type|action" + description varchar, + PRIMARY KEY (ns,name) +); +CREATE INDEX role_name ON role(name); + +// Will be cached +CREATE TABLE perm ( + ns varchar, + type varchar, + instance varchar, + action varchar, + roles set<varchar>, // Need to find Roles given Permissions + description varchar, + PRIMARY KEY (ns,type,instance,action) +); + +// This table is user for Authorization +CREATE TABLE user_role ( + user varchar, + role varchar, // deprecated: change to ns/rname after 2.0.11 + ns varchar, + rname varchar, + expires timestamp, + PRIMARY KEY(user,role) + ); +CREATE INDEX user_role_ns ON user_role(ns); +CREATE INDEX user_role_role ON user_role(role); + +// This table is only for the case where return User Credential (MechID) Authentication +CREATE TABLE cred ( + id varchar, + type int, + expires timestamp, + ns varchar, + other int, + notes varchar, + cred blob, + prev blob, + PRIMARY KEY (id,type,expires) + ); +CREATE INDEX cred_ns ON cred(ns); + +// Certificate Cross Table +// coordinated with CRED type 2 +CREATE TABLE cert ( + fingerprint blob, + id varchar, + x500 varchar, + expires timestamp, + PRIMARY KEY (fingerprint) + ); +CREATE INDEX cert_id ON cert(id); +CREATE INDEX cert_x500 ON cert(x500); + +CREATE TABLE notify ( + user text, + type int, + last timestamp, + checksum int, + PRIMARY KEY (user,type) +); + +CREATE TABLE x509 ( + ca text, + serial blob, + id text, + x500 text, + x509 text, + PRIMARY KEY (ca,serial) +); + + +CREATE INDEX x509_id ON x509 (id); +CREATE INDEX x509_x500 ON x509 (x500); + +// +// Deployment Artifact (for Certman) +// +CREATE TABLE artifact ( + mechid text, + machine text, + type Set<text>, + sponsor text, + ca text, + dir text, + appName text, + os_user text, + notify text, + expires timestamp, + renewDays int, + PRIMARY KEY (mechid,machine) +); +CREATE INDEX artifact_machine ON artifact(machine); + +// +// Non-Critical Table functions +// +// Table Info - for Caching +CREATE TABLE cache ( + name varchar, + seg int, // cache Segment + touched timestamp, + PRIMARY KEY(name,seg) +); + +CREATE TABLE history ( + id timeuuid, + yr_mon int, + user varchar, + action varchar, + target varchar, // user, user_role, + subject varchar, // field for searching main portion of target key + memo varchar, //description of the action + reconstruct blob, //serialized form of the target + // detail Map<varchar, varchar>, // additional information + PRIMARY KEY (id) +); +CREATE INDEX history_yr_mon ON history(yr_mon); +CREATE INDEX history_user ON history(user); +CREATE INDEX history_subject ON history(subject); + +// +// A place to hold objects to be created at a future time. +// +CREATE TABLE future ( + id uuid, // uniquify + target varchar, // Target Table + memo varchar, // Description + start timestamp, // When it should take effect + expires timestamp, // When not longer valid + construct blob, // How to construct this object (like History) + PRIMARY KEY(id) +); +CREATE INDEX future_idx ON future(target); +CREATE INDEX future_start_idx ON future(start); + + +CREATE TABLE approval ( + id timeuuid, // unique Key + ticket uuid, // Link to Future Record + user varchar, // the user who needs to be approved + approver varchar, // user approving + type varchar, // approver types i.e. Supervisor, Owner + status varchar, // approval status. pending, approved, denied + memo varchar, // Text for Approval to know what's going on + operation varchar, // List operation to perform + PRIMARY KEY(id) + ); +CREATE INDEX appr_approver_idx ON approval(approver); +CREATE INDEX appr_user_idx ON approval(user); +CREATE INDEX appr_ticket_idx ON approval(ticket); +CREATE INDEX appr_status_idx ON approval(status); + +CREATE TABLE delegate ( + user varchar, + delegate varchar, + expires timestamp, + PRIMARY KEY (user) +); +CREATE INDEX delg_delg_idx ON delegate(delegate); + +// +// Used by authz-batch processes to ensure only 1 runs at a time +// +CREATE TABLE run_lock ( + class text, + host text, + start timestamp, + PRIMARY KEY ((class)) +); diff --git a/auth/auth-service/src/main/resources/docker-compose/data2/.gitignore b/auth/auth-service/src/main/resources/docker-compose/data2/.gitignore new file mode 100644 index 00000000..b4e2528b --- /dev/null +++ b/auth/auth-service/src/main/resources/docker-compose/data2/.gitignore @@ -0,0 +1 @@ +/identities.dat diff --git a/auth/auth-service/src/main/resources/docker-compose/wait_for_host_port.sh b/auth/auth-service/src/main/resources/docker-compose/wait_for_host_port.sh new file mode 100644 index 00000000..e4e4bf9c --- /dev/null +++ b/auth/auth-service/src/main/resources/docker-compose/wait_for_host_port.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +set -e + +host="$1" +port="$2" +shift +shift +cmd="$@" + +until echo > /dev/tcp/${host}/${port} ; do + >&2 echo "${host}:${port} is unavailable - sleeping" + sleep 1 +done + +>&2 echo "${host}:${port} is up - executing command" +exec $cmd diff --git a/auth/auth-service/src/main/resources/docker/.gitignore b/auth/auth-service/src/main/resources/docker/.gitignore new file mode 100644 index 00000000..746c7bb0 --- /dev/null +++ b/auth/auth-service/src/main/resources/docker/.gitignore @@ -0,0 +1,5 @@ +/authAPI.props +/com.osaaf.common.props +/com.osaaf.props +/Dockerfile +/startup.sh diff --git a/auth/auth-service/src/main/resources/etc/.gitignore b/auth/auth-service/src/main/resources/etc/.gitignore new file mode 100644 index 00000000..d7251ce8 --- /dev/null +++ b/auth/auth-service/src/main/resources/etc/.gitignore @@ -0,0 +1,3 @@ +/authAPI.props +/com.osaaf.common.props +/com.osaaf.props |