diff options
Diffstat (limited to 'authz-service/src/main/java/com/att/authz/service')
19 files changed, 0 insertions, 8881 deletions
diff --git a/authz-service/src/main/java/com/att/authz/service/AuthAPI.java b/authz-service/src/main/java/com/att/authz/service/AuthAPI.java deleted file mode 100644 index 6a5b0453..00000000 --- a/authz-service/src/main/java/com/att/authz/service/AuthAPI.java +++ /dev/null @@ -1,330 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service;
-
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.security.GeneralSecurityException;
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.List;
-import java.util.Properties;
-
-import com.att.aft.dme2.api.DME2Exception;
-//import com.att.aft.dme2.api.DME2FilterHolder;
-//import com.att.aft.dme2.api.DME2FilterHolder.RequestDispatcherType;
-import com.att.aft.dme2.api.DME2Manager;
-import com.att.aft.dme2.api.DME2Server;
-import com.att.aft.dme2.api.DME2ServerProperties;
-import com.att.aft.dme2.api.DME2ServiceHolder;
-import com.att.aft.dme2.api.util.DME2FilterHolder;
-import com.att.aft.dme2.api.util.DME2FilterHolder.RequestDispatcherType;
-import com.att.aft.dme2.api.util.DME2ServletHolder;
-//import com.att.aft.dme2.api.DME2ServletHolder;
-import com.att.authz.cadi.DirectAAFLur;
-import com.att.authz.cadi.DirectAAFUserPass;
-import com.att.authz.cadi.DirectCertIdentity;
-import com.att.authz.env.AuthzEnv;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.env.AuthzTransFilter;
-import com.att.authz.facade.AuthzFacadeFactory;
-import com.att.authz.facade.AuthzFacade_2_0;
-import com.att.authz.org.OrganizationFactory;
-import com.att.authz.server.AbsServer;
-import com.att.authz.service.api.API_Api;
-import com.att.authz.service.api.API_Approval;
-import com.att.authz.service.api.API_Creds;
-import com.att.authz.service.api.API_Delegate;
-import com.att.authz.service.api.API_History;
-import com.att.authz.service.api.API_Mgmt;
-import com.att.authz.service.api.API_NS;
-import com.att.authz.service.api.API_Perms;
-import com.att.authz.service.api.API_Roles;
-import com.att.authz.service.api.API_User;
-import com.att.authz.service.api.API_UserRole;
-import com.att.authz.service.mapper.Mapper.API;
-import com.att.cadi.CadiException;
-import com.att.cadi.LocatorException;
-import com.att.cadi.SecuritySetter;
-import com.att.cadi.aaf.v2_0.AAFTrustChecker;
-import com.att.cadi.config.Config;
-import com.att.cadi.config.SecurityInfoC;
-import com.att.cadi.http.HBasicAuthSS;
-import com.att.cadi.http.HMangr;
-import com.att.cadi.http.HX509SS;
-import com.att.cadi.locator.DME2Locator;
-import com.att.cadi.taf.basic.BasicHttpTaf;
-import com.att.cssa.rserv.HttpMethods;
-import com.att.dao.CassAccess;
-import com.att.dao.aaf.cass.CacheInfoDAO;
-import com.att.dao.aaf.hl.Question;
-import com.att.inno.env.APIException;
-import com.att.inno.env.Data;
-import com.att.inno.env.Env;
-import com.datastax.driver.core.Cluster;
-
-public class AuthAPI extends AbsServer {
-
- private static final String ORGANIZATION = "Organization.";
- private static final String DOMAIN = "openecomp.org";
-
-// 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;
-
- /**
- * Construct AuthzAPI with all the Context Supporting Routes that Authz needs
- *
- * @param env
- * @param decryptor
- * @throws APIException
- */
- public AuthAPI(AuthzEnv env) throws Exception {
- super(env,"AAF");
-
- // Set "aaf_url" for peer communication based on Service DME2 URL
- env.setProperty(Config.AAF_URL, "https://DME2RESOLVE/"+env.getProperty("DMEServiceName"));
-
- // Setup Log Names
- env.setLog4JNames("log4j.properties","authz","authz|service","audit","init","trace");
-
- final Cluster cluster = com.att.dao.CassAccess.cluster(env,null);
-
- // jg 4/2015 SessionFilter unneeded... DataStax already deals with Multithreading well
-
- // Setup Shutdown Hooks for Cluster and Pooled Sessions
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public void run() {
-// sessionFilter.destroy();
- cluster.close();
- }
- });
-
- // Initialize Facade for all uses
- AuthzTrans trans = env.newTrans();
-
- // 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));
- }
- }
-
- // 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);
-
- 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,trans.getProperty("Unknown"));
-
-
- // 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);
-
- }
-
- /**
- * 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 AuthzAPI as DME2 Service
- * @param env
- * @param props
- * @throws Exception
- * @throws LocatorException
- * @throws CadiException
- * @throws NumberFormatException
- * @throws IOException
- * @throws GeneralSecurityException
- * @throws APIException
- */
- public void startDME2(Properties props) throws Exception {
- DME2Manager dme2 = new DME2Manager("AuthzServiceDME2Manager",props);
- String s = dme2.getStringProp(Config.AFT_DME2_SSL_INCLUDE_PROTOCOLS,null);
- env.init().log("DME2 Service TLS Protocols are set to",(s==null?"DME2 Default":s));
-
- DME2ServiceHolder svcHolder;
- List<DME2ServletHolder> slist = new ArrayList<DME2ServletHolder>();
- svcHolder = new DME2ServiceHolder();
- String serviceName = env.getProperty("DMEServiceName",null);
- if(serviceName!=null) {
- svcHolder.setServiceURI(serviceName);
- svcHolder.setManager(dme2);
- svcHolder.setContext("/");
- DME2ServletHolder srvHolder = new DME2ServletHolder(this, new String[]{"/authz","/authn","/mgmt"});
- srvHolder.setContextPath("/*");
- slist.add(srvHolder);
-
- EnumSet<RequestDispatcherType> edlist = EnumSet.of(
- RequestDispatcherType.REQUEST,
- RequestDispatcherType.FORWARD,
- RequestDispatcherType.ASYNC
- );
-
- List<DME2FilterHolder> flist = new ArrayList<DME2FilterHolder>();
-
- // Add DME2 Metrics
- // DME2 removed the Metrics Filter in 2.8.8.5
- // flist.add(new DME2FilterHolder(new DME2MetricsFilter(serviceName),"/*",edlist));
-
- // Note: Need CADI to fill out User for AuthTransFilter... so it's first
- // Make sure there is no AAF TAF configured for Filters
- env.setProperty(Config.AAF_URL,null);
-
- flist.add(
- new DME2FilterHolder(
- 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 BasicHttpTaf(env, directAAFUserPass,
- DOMAIN,Long.parseLong(env.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)),
- false
- ) // Add specialty Direct TAF
- ),
- "/*", edlist));
-
- svcHolder.setFilters(flist);
- svcHolder.setServletHolders(slist);
-
- DME2Server dme2svr = dme2.getServer();
-
- String hostname = env.getProperty("HOSTNAME",null);
- if(hostname!=null) {
- //dme2svr.setHostname(hostname);
- hostname=null;
- }
- // dme2svr.setGracefulShutdownTimeMs(5000);
-
- env.init().log("Starting AAF Jetty/DME2 server...");
- dme2svr.start();
- try {
-// if(env.getProperty("NO_REGISTER",null)!=null)
- dme2.bindService(svcHolder);
- //env.init().log("DME2 is available as HTTPS on port:",dme2svr.getPort());
-
- // Start CacheInfo Listener
- HMangr hman = new HMangr(env, new DME2Locator(env, dme2,"https://DME2RESOLVE/"+serviceName,true /*remove self from cache*/));
- SecuritySetter<HttpURLConnection> ss;
-
-// InetAddress ip = InetAddress.getByName(dme2svr.getHostname());
- SecurityInfoC<HttpURLConnection> si = new SecurityInfoC<HttpURLConnection>(env);
- String mechID;
- if((mechID=env.getProperty(Config.AAF_MECHID))==null) {
- String alias = env.getProperty(Config.CADI_ALIAS);
- if(alias==null) {
- env.init().log(Config.CADI_ALIAS, "is required for AAF Authentication by Certificate. Alternately, set",Config.AAF_MECHID,"and",Config.AAF_MECHPASS);
- System.exit(1);
- }
- ss = new HX509SS(alias,si,true);
- env.init().log("X509 Certificate Client configured:", alias);
- } else {
- String pass = env.getProperty(Config.AAF_MECHPASS);
- if(pass==null) {
- env.init().log(Config.AAF_MECHPASS, "is required for AAF Authentication by ID/Pass");
- System.exit(1);
- }
- ss = new HBasicAuthSS(mechID,env.decrypt(pass, true),si,true);
- env.init().log("BasicAuth (ID/Pass) Client configured.");
- }
-
- //TODO Reenable Cache Update
- //CacheInfoDAO.startUpdate(env, hman, ss, dme2svr.getHostname(), dme2svr.getPort());
-
- while(true) { // Per DME2 Examples...
- Thread.sleep(5000);
- }
- } catch(DME2Exception e) { // Error binding service doesn't seem to stop DME2 or Process
- env.init().log(e,"DME2 Initialization Error");
- dme2svr.stop();
- System.exit(1);
- } catch(InterruptedException e) {
- env.init().log("AAF Jetty Server interrupted!");
- }
- } else {
- env.init().log("Properties must contain 'DMEServiceName'");
- }
- }
-
- public static void main(String[] args) {
- setup(AuthAPI.class,"authAPI.props");
- }
-}
diff --git a/authz-service/src/main/java/com/att/authz/service/AuthzCassServiceImpl.java b/authz-service/src/main/java/com/att/authz/service/AuthzCassServiceImpl.java deleted file mode 100644 index dcd02739..00000000 --- a/authz-service/src/main/java/com/att/authz/service/AuthzCassServiceImpl.java +++ /dev/null @@ -1,3972 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service;
-
-import static com.att.authz.layer.Result.OK;
-import static com.att.cssa.rserv.HttpMethods.DELETE;
-import static com.att.cssa.rserv.HttpMethods.GET;
-import static com.att.cssa.rserv.HttpMethods.POST;
-import static com.att.cssa.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 com.att.authz.common.Define;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.layer.Result;
-import com.att.authz.org.Executor;
-import com.att.authz.org.Organization;
-import com.att.authz.org.Organization.Expiration;
-import com.att.authz.org.Organization.Identity;
-import com.att.authz.org.Organization.Policy;
-import com.att.authz.service.mapper.Mapper;
-import com.att.authz.service.mapper.Mapper.API;
-import com.att.authz.service.validation.Validator;
-import com.att.cadi.principal.BasicPrincipal;
-import com.att.cssa.rserv.doc.ApiDoc;
-import com.att.dao.DAOException;
-import com.att.dao.aaf.cass.ApprovalDAO;
-import com.att.dao.aaf.cass.CertDAO;
-import com.att.dao.aaf.cass.CredDAO;
-import com.att.dao.aaf.cass.DelegateDAO;
-import com.att.dao.aaf.cass.FutureDAO;
-import com.att.dao.aaf.cass.HistoryDAO;
-import com.att.dao.aaf.cass.Namespace;
-import com.att.dao.aaf.cass.NsDAO;
-import com.att.dao.aaf.cass.NsDAO.Data;
-import com.att.dao.aaf.cass.NsSplit;
-import com.att.dao.aaf.cass.NsType;
-import com.att.dao.aaf.cass.PermDAO;
-import com.att.dao.aaf.cass.RoleDAO;
-import com.att.dao.aaf.cass.Status;
-import com.att.dao.aaf.cass.UserRoleDAO;
-import com.att.dao.aaf.hl.CassExecutor;
-import com.att.dao.aaf.hl.Function;
-import com.att.dao.aaf.hl.Question;
-import com.att.dao.aaf.hl.Question.Access;
-import com.att.inno.env.Env;
-import com.att.inno.env.TimeTaken;
-import com.att.inno.env.util.Chrono;
-import com.att.inno.env.util.Split;
-
-import aaf.v2_0.CredRequest;
-
-/**
- * AuthzCassServiceImpl implements AuthzCassService for
- *
- *
- * @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 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 com.att.authz.service.AuthzService#createNS(com.att.authz.env.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 Validator v = new Validator();
- 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<List<Identity>> rfc = func.createFuture(trans, fd.value, namespace.name, trans.user(),parentNs.value, "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 com.att.authz.service.AuthzService#applyModel(com.att.authz.env.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 Validator();
- 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(), Define.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 Validator();
- if(v.nullOrBlank("Key",key).err()) {
- return Result.err(Status.ERR_BadData,v.errs());
- }
-
- // May Read
- if(!ques.isGranted(trans, trans.user(), Define.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 Validator();
- 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(), Define.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 Validator();
- 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(), Define.ROOT_NS, "attrib", ":com.att.*:"+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 Validator();
- 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 Validator();
- 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 Validator();
- 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 Validator();
- 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 Validator();
- 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 Validator v = new Validator();
- 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 com.att.authz.service.AuthzService#deleteNS(com.att.authz.env.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 com.att.authz.service.AuthzService#createOrUpdatePerm(com.att.authz.env.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 Validator v = new Validator(trans);
- 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<List<Identity>> rfc = func.createFuture(trans,fd.value,
- newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action,
- trans.user(),
- nsr.value.get(0),
- "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 Validator();
- 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 Validator();
- 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 Validator();
- if(v.nullOrBlank("User", user).err()) {
- return Result.err(Status.ERR_BadData,v.errs());
- }
-
- Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user, trans.forceRequested());
- 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 = 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 Validator();
- if(v.nullOrBlank("User", user).err()) {
- return Result.err(Status.ERR_BadData,v.errs());
- }
-
- //////////////
- Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user,trans.forceRequested());
- 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 Validator();
- 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.forceRequested());
- 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 Validator();
- 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 Validator v = new Validator(trans);
- 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 Validator v = new Validator(trans);
- 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 Validator v = new Validator(trans);
- 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 Validator v = new Validator(trans);
- 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<List<Identity>> rfc = func.createFuture(trans, fd.value,
- perm.encode(), trans.user(),nsr.value.get(0),"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.forceRequested(), 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 Validator(trans);
- 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.forceRequested(), 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.osaaf - A Possible root Namespace for maintaining 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 Validator v = new Validator(trans);
- 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<List<Identity>> rfc = func.createFuture(trans, fd.value,
- role.encode(), trans.user(),nsr.value.get(0),"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 com.att.authz.service.AuthzService#getRolesByName(com.att.authz.env.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 Validator();
- 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 com.att.authz.service.AuthzService#getRolesByUser(com.att.authz.env.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 Validator();
- 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 com.att.authz.service.AuthzService#getRolesByNS(com.att.authz.env.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 Validator();
- 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 com.att.authz.service.AuthzService#getRolesByNS(com.att.authz.env.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 Validator();
- 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 Validator(trans);
- 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 Validator v = new Validator(trans);
- 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 Validator v = new Validator(trans);
- 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.forceRequested()) {
- // 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<List<Identity>> rfc = func.createFuture(trans,fd.value,
- rpd.value.fullPerm(),
- trans.user(),
- nsr.value.get(0),
- "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);
- }
-
- }
-
- /**
- * Create a RoleDAO.Data
- * @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 Validator v = new Validator(trans);
- if(v.nullOrBlank(updt.value)
- .nullOrBlank(rrd.value)
- .err()) {
- return Result.err(Status.ERR_BadData,v.errs());
- }
-
- Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, updt.value.ns, updt.value.type,
- updt.value.instance, updt.value.action);
-
- if(rlpd.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);
- }
-
- Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, updt.value,true, // allow ungrants requests
- new Mapper.Memo() {
- @Override
- public String get() {
- return "Ungrant Permission [" + updt.value.fullPerm() + ']' +
- " from Role [" + rrd.value.fullName() + "]";
- }
- },
- new MayChange() {
- private Result<NsDAO.Data> nsd;
- @Override
- public Result<?> mayChange() {
- if(nsd==null) {
- nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write);
- }
- return nsd;
- }
- });
- Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, updt.value.ns);
- if(nsr.notOKorIsEmpty()) {
- return Result.err(nsr);
- }
- switch(fd.status) {
- case OK:
- Result<List<Identity>> rfc = func.createFuture(trans,fd.value,
- updt.value.fullPerm(),
- trans.user(),
- nsr.value.get(0),
- "UG"
- );
- if(rfc.isOK()) {
- return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
- updt.value.ns,
- updt.value.type,
- updt.value.instance,
- updt.value.action);
- } else {
- return Result.err(rfc);
- }
- case Status.ACC_Now:
- return func.delPermFromRole(trans, rrd.value, updt.value, false);
- default:
- return Result.err(fd);
- }
- }
-
- @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 Validator v = new Validator(trans);
- 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 Validator v = new Validator(trans);
- 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.forceRequested()) {
- 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<List<Identity>> rfc = func.createFuture(trans, fd.value,
- role.encode(), trans.user(),nsr.value.get(0),"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.forceRequested(), 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(), Define.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()) {
- rcred = ques.userCredSetup(trans, rcred.value);
-
- final Validator v = new Validator();
-
- if(v.cred(trans.org(),rcred,true).err()) { // Note: Creates have stricter Validations
- return Result.err(Status.ERR_BadData,v.errs());
- }
-
-
- // 2016-4 JG, 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");
- }
- for (CredDAO.Data curr : rlcd.value) {
- 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 JG 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<List<Identity>> rfc = func.createFuture(trans, fd.value,
- rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires,
- trans.user(), nsr.value.get(0), "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 Validator();
- 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 Validator();
- 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 Validator v = new Validator();
-
- if(v.cred(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<List<Identity>> rfc = func.createFuture(trans, fd.value,
- rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires,
- trans.user(), nsr.value.get(0), "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();
- // If user resets password in same day, we will have a primary key conflict, so subtract 1 day
- if (rlcd.value.get(entry).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();
- }
-
- 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 Validator v = new Validator();
- 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.cred = found.cred;
- cd.type = found.type;
- 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 Validator();
- 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.forceRequested()) {
- 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 {
- entry = Integer.parseInt(inputOption) - 1;
- } 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<List<Identity>> rfc = func.createFuture(trans, fd.value, cred.value.id,
- trans.user(), nsr.value.get(0),"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.forceRequested()) {
- 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
- 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 = { "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 Validator v = new Validator();
- 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<List<Identity>> rfc = func.createFuture(trans, fd.value, userRole.user+'|'+userRole.ns + '.' + userRole.rname,
- userRole.user, nsr.value, "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 Validator(trans);
- 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 Validator(trans);
- 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);
- }
- @SuppressWarnings("unchecked")
- USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES);
- // Checked for permission
- mapper.userRoles(trans, rlurd.value, 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 Validator v = new Validator();
- 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, true);
- 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 Validator v = new Validator();
- 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, true);
- 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 Validator v = new Validator();
- 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.futureRequested()) {
- 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<List<Identity>> rfc = func.createFuture(trans, fto,
- userRole.user+'|'+userRole.role, userRole.user, rcr.value, "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 Validator();
- 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;
- // Make sure we don't delete the last owner
- if(Question.OWNER.equals(rdd.name) && ques.countOwner(trans, usr, rdd.ns)<=1) {
- return Result.err(Status.ERR_Denied,"You may not delete the last Owner of " + rdd.ns );
- }
-
- Result<NsDAO.Data> rns = ques.mayUser(trans, trans.user(), rdd, Access.write);
- if(mayNotChange=rns.notOK()) {
- if(!trans.futureRequested()) {
- 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<List<Identity>> rfc = func.createFuture(trans, fto,
- userRole.user+'|'+userRole.role, userRole.user, rns.value, "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 Validator();
- 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 Validator();
- 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);
- }
- 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.readByRole(trans, 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);
- }
-
- /**
- * 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 Validator(trans);
- 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 Validator(trans);
- 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 Validator(trans);
- 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 Validator(trans);
- 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 Validator(trans);
- 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 Validator v = new Validator();
- 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<List<Identity>> rfc = func.createFuture(trans, fd.value,
- dd.user, trans.user(),null, access==Access.create?"C":"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 Validator();
- 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 Validator();
- 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 Validator();
- 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 Validator();
- 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
- ***********************************/
- @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;
- for(ApprovalDAO.Data updt : rlad.value) {
- if(updt.ticket!=null) {
- curr = ques.approvalDAO.readByTicket(trans, updt.ticket);
- } 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()) {
- for(ApprovalDAO.Data cd : curr.value){
- // Check for right record. Need ID, or (Ticket&Trans.User==Appr)
- // If Default ID
- boolean delegatedAction = ques.isDelegated(trans, user, cd.approver);
- 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)) {
- cd.id = changed(updt.id,cd.id);
- cd.ticket = changed(updt.ticket,cd.ticket);
- cd.user = changed(updt.user,cd.user);
- cd.approver = changed(updt.approver,cd.approver);
- cd.type = changed(updt.type,cd.type);
- cd.status = changed(updt.status,cd.status);
- cd.memo = changed(updt.memo,cd.memo);
- cd.operation = changed(updt.operation,cd.operation);
- cd.updated = changed(updt.updated,cd.updated);
- ques.approvalDAO.update(trans, cd);
- Result<Void> rv = func.performFutureOp(trans, cd);
- if (rv.isOK()) {
- if (delegatedAction) {
- trans.audit().log("actor=",user,",action=",updt.status,",operation=\"",cd.memo,
- '"',",requestor=",cd.user,",delegator=",delegator);
- }
- if (!delegatedAction && cd.status.equalsIgnoreCase("denied")) {
- trans.audit().log("actor=",trans.user(),",action=denied,operation=\"",cd.memo,'"',",requestor=",cd.user);
- }
- rv = ques.approvalDAO.delete(trans, cd, false);
- }
- ++numProcessed;
-
- }
- }
- }
- }
- }
-
- if(numApprs==numProcessed) {
- return Result.ok();
- }
- return Result.err(Status.ERR_ActionNotCompleted,numProcessed + " out of " + numApprs + " completed");
-
- }
-
- private<T> T changed(T src, T dflt) {
- if(src!=null) {
- return src;
- }
- return dflt;
- }
-
- @Override
- public Result<APPROVALS> getApprovalsByUser(AuthzTrans trans, String user) {
- final Validator v = new Validator();
- 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 Validator();
- 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 Validator();
- 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 com.att.authz.service.AuthzService#clearCache(com.att.authz.env.AuthzTrans, java.lang.String)
- */
- @Override
- public Result<Void> cacheClear(AuthzTrans trans, String cname) {
- if(ques.isGranted(trans,trans.user(),Define.ROOT_NS,CACHE,cname,"clear")) {
- return ques.clearCache(trans,cname);
- }
- return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.cache|%s|clear",
- trans.user(),Define.ROOT_NS,cname);
- }
-
- /* (non-Javadoc)
- * @see com.att.authz.service.AuthzService#cacheClear(com.att.authz.env.AuthzTrans, java.lang.String, java.lang.Integer)
- */
- @Override
- public Result<Void> cacheClear(AuthzTrans trans, String cname, int[] segment) {
- if(ques.isGranted(trans,trans.user(),Define.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.cache|%s|clear",
- trans.user(),Define.ROOT_NS,cname);
- }
-
- /* (non-Javadoc)
- * @see com.att.authz.service.AuthzService#dbReset(com.att.authz.env.AuthzTrans)
- */
- @Override
- public void dbReset(AuthzTrans trans) {
- ques.historyDAO.reportPerhapsReset(trans, null);
- }
-
-}
-
diff --git a/authz-service/src/main/java/com/att/authz/service/AuthzService.java b/authz-service/src/main/java/com/att/authz/service/AuthzService.java deleted file mode 100644 index f766364a..00000000 --- a/authz-service/src/main/java/com/att/authz/service/AuthzService.java +++ /dev/null @@ -1,748 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service;
-
-import java.util.Date;
-
-import javax.servlet.http.HttpServletRequest;
-
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.layer.Result;
-import com.att.authz.service.mapper.Mapper;
-import com.att.dao.DAOException;
-import com.att.dao.aaf.cass.NsType;
-
-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
- *
- * 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);
-
-
- /**
- *
- * @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/authz-service/src/main/java/com/att/authz/service/Code.java b/authz-service/src/main/java/com/att/authz/service/Code.java deleted file mode 100644 index b70712c3..00000000 --- a/authz-service/src/main/java/com/att/authz/service/Code.java +++ /dev/null @@ -1,45 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service;
-
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.cssa.rserv.HttpCode;
-
-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;
- }
-
-}
diff --git a/authz-service/src/main/java/com/att/authz/service/MayChange.java b/authz-service/src/main/java/com/att/authz/service/MayChange.java deleted file mode 100644 index 651a5172..00000000 --- a/authz-service/src/main/java/com/att/authz/service/MayChange.java +++ /dev/null @@ -1,33 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service;
-
-import com.att.authz.layer.Result;
-
-/**
- * There are several ways to determine if
- *
- */
-public interface MayChange {
- public Result<?> mayChange();
-}
diff --git a/authz-service/src/main/java/com/att/authz/service/api/API_Api.java b/authz-service/src/main/java/com/att/authz/service/api/API_Api.java deleted file mode 100644 index d0e67447..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_Api.java +++ /dev/null @@ -1,92 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-import com.att.cadi.Symm;
-import com.att.cssa.rserv.HttpMethods;
-
-/**
- * API Apis
- *
- */
-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 AuthAPI 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/authz-service/src/main/java/com/att/authz/service/api/API_Approval.java b/authz-service/src/main/java/com/att/authz/service/api/API_Approval.java deleted file mode 100644 index c8eb18ca..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_Approval.java +++ /dev/null @@ -1,107 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import static com.att.cssa.rserv.HttpMethods.GET;
-import static com.att.cssa.rserv.HttpMethods.PUT;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-
-public class API_Approval {
- // Hide Public Constructor
- private API_Approval() {}
-
- public static void init(AuthAPI 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.VOID,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/authz-service/src/main/java/com/att/authz/service/api/API_Creds.java b/authz-service/src/main/java/com/att/authz/service/api/API_Creds.java deleted file mode 100644 index f204f1bb..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_Creds.java +++ /dev/null @@ -1,277 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import static com.att.cssa.rserv.HttpMethods.DELETE;
-import static com.att.cssa.rserv.HttpMethods.GET;
-import static com.att.cssa.rserv.HttpMethods.POST;
-import static com.att.cssa.rserv.HttpMethods.PUT;
-
-import java.security.Principal;
-import java.util.Date;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.cadi.DirectAAFUserPass;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-import com.att.cadi.CredVal;
-import com.att.cadi.Symm;
-import com.att.cadi.principal.BasicPrincipal;
-import com.att.cadi.principal.X509Principal;
-import com.att.cssa.rserv.HttpMethods;
-import com.att.inno.env.Env;
-
-/**
- * Initialize All Dispatches related to Credentials (AUTHN)
- *
- */
-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, AuthAPI 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 ba = req.getHeader("Authorization");
- if(ba.startsWith("Basic ")) {
- String decoded = Symm.base64noSplit.decode(ba.substring(6));
- int colon = decoded.indexOf(':');
- if(directAAFUserPass.validate(
- decoded.substring(0,colon),
- CredVal.Type.PASSWORD ,
- decoded.substring(colon+1).getBytes())) {
-
- resp.setStatus(HttpStatus.OK_200);
- } else {
- resp.setStatus(HttpStatus.FORBIDDEN_403);
- }
- }
- } 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
- 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(AuthAPI 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/authz-service/src/main/java/com/att/authz/service/api/API_Delegate.java b/authz-service/src/main/java/com/att/authz/service/api/API_Delegate.java deleted file mode 100644 index 15e7eeb3..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_Delegate.java +++ /dev/null @@ -1,153 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import static com.att.authz.layer.Result.OK;
-import static com.att.cssa.rserv.HttpMethods.DELETE;
-import static com.att.cssa.rserv.HttpMethods.GET;
-import static com.att.cssa.rserv.HttpMethods.POST;
-import static com.att.cssa.rserv.HttpMethods.PUT;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-
-public class API_Delegate {
- public static void init(AuthAPI 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/authz-service/src/main/java/com/att/authz/service/api/API_History.java b/authz-service/src/main/java/com/att/authz/service/api/API_History.java deleted file mode 100644 index a4702cf6..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_History.java +++ /dev/null @@ -1,238 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import static com.att.authz.layer.Result.OK;
-import static com.att.cssa.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 com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-import com.att.dao.aaf.cass.Status;
-
-/**
- * Pull certain types of History Info
- *
- * Specify yyyymm as
- * single - 201504
- * commas 201503,201504
- * ranges 201501-201504
- * combinations 201301,201401,201501-201504
- *
- *
- */
-public class API_History {
- /**
- * Normal Init level APIs
- *
- * @param authzAPI
- * @param facade
- * @throws Exception
- */
- public static void init(AuthAPI 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/authz-service/src/main/java/com/att/authz/service/api/API_Mgmt.java b/authz-service/src/main/java/com/att/authz/service/api/API_Mgmt.java deleted file mode 100644 index 6df08454..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_Mgmt.java +++ /dev/null @@ -1,274 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import static com.att.authz.layer.Result.OK;
-import static com.att.cssa.rserv.HttpMethods.DELETE;
-import static com.att.cssa.rserv.HttpMethods.POST;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.common.Define;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-import com.att.cadi.taf.dos.DenialOfServiceTaf;
-import com.att.dao.aaf.cass.Status;
-import com.att.dao.aaf.hl.Question;
-import com.att.dao.session.SessionFilter;
-import com.att.inno.env.Trans;
-
-/**
- * User Role APIs
- *
- */
-public class API_Mgmt {
-
- private static final String SUCCESS = "SUCCESS";
-
- /**
- * Normal Init level APIs
- *
- * @param authzAPI
- * @param facade
- * @throws Exception
- */
- public static void init(final AuthAPI 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(Define.ROOT_NS+".db|pool|clear")) {
- SessionFilter.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(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|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(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|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(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|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(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|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(Define.ROOT_NS+".log|"+Define.ROOT_COMPANY+"|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(Define.ROOT_NS+".log|"+Define.ROOT_COMPANY+"|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/authz-service/src/main/java/com/att/authz/service/api/API_NS.java b/authz-service/src/main/java/com/att/authz/service/api/API_NS.java deleted file mode 100644 index 6b5c2dd8..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_NS.java +++ /dev/null @@ -1,396 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import static com.att.authz.layer.Result.OK;
-import static com.att.cssa.rserv.HttpMethods.DELETE;
-import static com.att.cssa.rserv.HttpMethods.GET;
-import static com.att.cssa.rserv.HttpMethods.POST;
-import static com.att.cssa.rserv.HttpMethods.PUT;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-import com.att.dao.aaf.cass.NsType;
-import com.att.dao.aaf.cass.Status;
-
-public class API_NS {
- private static final String FULL = "full";
- private static final String TRUE = "true";
-
- public static void init(AuthAPI 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/authz-service/src/main/java/com/att/authz/service/api/API_Perms.java b/authz-service/src/main/java/com/att/authz/service/api/API_Perms.java deleted file mode 100644 index 3c45a7a6..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_Perms.java +++ /dev/null @@ -1,291 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import static com.att.authz.layer.Result.OK;
-import static com.att.cssa.rserv.HttpMethods.DELETE;
-import static com.att.cssa.rserv.HttpMethods.GET;
-import static com.att.cssa.rserv.HttpMethods.POST;
-import static com.att.cssa.rserv.HttpMethods.PUT;
-
-import java.net.URLDecoder;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-import com.att.cadi.config.Config;
-
-public class API_Perms {
- public static void timeSensitiveInit(AuthAPI 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 {
-
- Result<Void> r = context.getPermsByUser(trans, resp, pathParam(req, "user"));
- 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(AuthAPI 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/authz-service/src/main/java/com/att/authz/service/api/API_Roles.java b/authz-service/src/main/java/com/att/authz/service/api/API_Roles.java deleted file mode 100644 index a8e8a395..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_Roles.java +++ /dev/null @@ -1,313 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import static com.att.authz.layer.Result.OK;
-import static com.att.cssa.rserv.HttpMethods.DELETE;
-import static com.att.cssa.rserv.HttpMethods.GET;
-import static com.att.cssa.rserv.HttpMethods.POST;
-import static com.att.cssa.rserv.HttpMethods.PUT;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-import com.att.dao.aaf.cass.Status;
-
-public class API_Roles {
- public static void init(AuthAPI 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
- */
- 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);
- }
- }
-
- }
- );
-
- }
-}
diff --git a/authz-service/src/main/java/com/att/authz/service/api/API_User.java b/authz-service/src/main/java/com/att/authz/service/api/API_User.java deleted file mode 100644 index 8d8fea84..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_User.java +++ /dev/null @@ -1,133 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import static com.att.authz.layer.Result.OK;
-import static com.att.cssa.rserv.HttpMethods.GET;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-
-/**
- * User Role APIs
- *
- */
-public class API_User {
- /**
- * Normal Init level APIs
- *
- * @param authzAPI
- * @param facade
- * @throws Exception
- */
- public static void init(final AuthAPI 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/authz-service/src/main/java/com/att/authz/service/api/API_UserRole.java b/authz-service/src/main/java/com/att/authz/service/api/API_UserRole.java deleted file mode 100644 index 96afb799..00000000 --- a/authz-service/src/main/java/com/att/authz/service/api/API_UserRole.java +++ /dev/null @@ -1,181 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.api;
-
-import static com.att.authz.layer.Result.OK;
-import static com.att.cssa.rserv.HttpMethods.DELETE;
-import static com.att.cssa.rserv.HttpMethods.GET;
-import static com.att.cssa.rserv.HttpMethods.POST;
-import static com.att.cssa.rserv.HttpMethods.PUT;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.att.aft.dme2.internal.jetty.http.HttpStatus;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.facade.AuthzFacade;
-import com.att.authz.layer.Result;
-import com.att.authz.service.AuthAPI;
-import com.att.authz.service.Code;
-import com.att.authz.service.mapper.Mapper.API;
-
-/**
- * User Role APIs
- *
- */
-public class API_UserRole {
- /**
- * Normal Init level APIs
- *
- * @param authzAPI
- * @param facade
- * @throws Exception
- */
- public static void init(final AuthAPI 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/authz-service/src/main/java/com/att/authz/service/mapper/Mapper.java b/authz-service/src/main/java/com/att/authz/service/mapper/Mapper.java deleted file mode 100644 index 626ba4b7..00000000 --- a/authz-service/src/main/java/com/att/authz/service/mapper/Mapper.java +++ /dev/null @@ -1,122 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.mapper;
-
-import java.util.Collection;
-import java.util.List;
-
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.layer.Result;
-import com.att.authz.service.MayChange;
-import com.att.dao.Bytification;
-import com.att.dao.aaf.cass.ApprovalDAO;
-import com.att.dao.aaf.cass.CertDAO;
-import com.att.dao.aaf.cass.CredDAO;
-import com.att.dao.aaf.cass.DelegateDAO;
-import com.att.dao.aaf.cass.FutureDAO;
-import com.att.dao.aaf.cass.HistoryDAO;
-import com.att.dao.aaf.cass.Namespace;
-import com.att.dao.aaf.cass.PermDAO;
-import com.att.dao.aaf.cass.RoleDAO;
-import com.att.dao.aaf.cass.UserRoleDAO;
-import com.att.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 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<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/authz-service/src/main/java/com/att/authz/service/mapper/Mapper_2_0.java b/authz-service/src/main/java/com/att/authz/service/mapper/Mapper_2_0.java deleted file mode 100644 index 67c929e8..00000000 --- a/authz-service/src/main/java/com/att/authz/service/mapper/Mapper_2_0.java +++ /dev/null @@ -1,790 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.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 com.att.authz.env.AuthzTrans;
-import com.att.authz.layer.Result;
-import com.att.authz.org.Organization;
-import com.att.authz.org.Organization.Expiration;
-import com.att.authz.service.MayChange;
-import com.att.cadi.aaf.marshal.CertsMarshal;
-import com.att.cadi.util.Vars;
-import com.att.cssa.rserv.Pair;
-import com.att.dao.Bytification;
-import com.att.dao.aaf.cass.ApprovalDAO;
-import com.att.dao.aaf.cass.CertDAO;
-import com.att.dao.aaf.cass.CredDAO;
-import com.att.dao.aaf.cass.DelegateDAO;
-import com.att.dao.aaf.cass.DelegateDAO.Data;
-import com.att.dao.aaf.cass.FutureDAO;
-import com.att.dao.aaf.cass.HistoryDAO;
-import com.att.dao.aaf.cass.Namespace;
-import com.att.dao.aaf.cass.NsSplit;
-import com.att.dao.aaf.cass.NsType;
-import com.att.dao.aaf.cass.PermDAO;
-import com.att.dao.aaf.cass.RoleDAO;
-import com.att.dao.aaf.cass.Status;
-import com.att.dao.aaf.cass.UserRoleDAO;
-import com.att.dao.aaf.hl.Question;
-import com.att.dao.aaf.hl.Question.Access;
-import com.att.inno.env.Env;
-import com.att.inno.env.TimeTaken;
-import com.att.inno.env.util.Chrono;
-import com.att.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.Nss.Ns.Attrib;
-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 com.att.authz.service.mapper.Mapper#ns(java.lang.Object, com.att.authz.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) {
- Attrib toAttrib = new 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);
- ns.getAdmin().addAll(nd.admin);
- ns.getResponsible().addAll(nd.owner);
- ns.setDescription(nd.description);
- if(nd.attrib!=null) {
- for(Pair<String,String> attrib : nd.attrib) {
- Attrib toAttrib = new 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();
- 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);
- 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 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 com.att.authz.service.mapper.Mapper#roles(java.util.List)
- */
- @Override
- public Result<Roles> roles(AuthzTrans trans, List<RoleDAO.Data> from, Roles to, boolean filter) {
- 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);
- 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 com.att.authz.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);
- user.setExpires(Chrono.timeStamp(urd.expires));
- cu.add(user);
- }
- return Result.ok(to);
- }
-
- /*
- * (non-Javadoc)
- * @see com.att.authz.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 future
- 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(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 = mc.mayChange();
- boolean needsAppr;
- if(needsAppr = rMayChange.notOK()) {
- if(enableApproval) {
- if(!trans.futureRequested()) {
- 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 com.att.authz.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());
- 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());
- }
-
-}
diff --git a/authz-service/src/main/java/com/att/authz/service/validation/Validator.java b/authz-service/src/main/java/com/att/authz/service/validation/Validator.java deleted file mode 100644 index e11c2688..00000000 --- a/authz-service/src/main/java/com/att/authz/service/validation/Validator.java +++ /dev/null @@ -1,386 +0,0 @@ -/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 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====================================================
- * *
- * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * *
- ******************************************************************************/
-package com.att.authz.service.validation;
-
-import java.util.regex.Pattern;
-
-import com.att.authz.cadi.DirectAAFLur.PermPermission;
-import com.att.authz.env.AuthzTrans;
-import com.att.authz.layer.Result;
-import com.att.authz.org.Organization;
-import com.att.dao.aaf.cass.CredDAO;
-import com.att.dao.aaf.cass.DelegateDAO;
-import com.att.dao.aaf.cass.Namespace;
-import com.att.dao.aaf.cass.PermDAO;
-import com.att.dao.aaf.cass.RoleDAO;
-import com.att.dao.aaf.cass.UserRoleDAO;
-
-/**
- * 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.
- *
- */
-public class Validator {
- // % () ,-. 0-9 =A-Z _a-z
- private static final String ESSENTIAL="\\x25\\x28\\x29\\x2C-\\x2E\\x30-\\x39\\x3D\\x40-\\x5A\\x5F\\x61-\\x7A";
- private static final Pattern ESSENTIAL_CHARS=Pattern.compile("["+ESSENTIAL+"]+");
-
- // Must be 1 or more of Alphanumeric or the following :._-
- // '*' only allowed when it is the only character, or the only element in a key separator
- // :* :hello:* :hello:*:there etc
- public static final Pattern ACTION_CHARS=Pattern.compile(
- "["+ESSENTIAL+"]+" + // All AlphaNumeric+
- "|\\*" // Just Star
- );
-
- public static final Pattern INST_CHARS=Pattern.compile(
- "["+ESSENTIAL+"]+[\\*]*" + // All AlphaNumeric+ possibly ending with *
- "|\\*" + // Just Star
- "|(([:/]\\*)|([:/][!]{0,1}["+ESSENTIAL+"]+[\\*]*[:/]*))+" // Key :asdf:*:sdf*:sdk
- );
-
- // Must be 1 or more of Alphanumeric or the following ._-, and be in the form id@domain
- public static final Pattern ID_CHARS=Pattern.compile("[\\w.-]+@[\\w.-]+");
- // Must be 1 or more of Alphanumeric or the following ._-
- public static final Pattern NAME_CHARS=Pattern.compile("[\\w.-]+");
-
- private final Pattern actionChars;
- private final Pattern instChars;
- private StringBuilder msgs;
-
- /**
- * Default Validator does not check for non-standard Action/Inst chars
- *
- *
- * IMPORTANT: Use ONLY when the Validator is doing something simple... NullOrBlank
- */
- public Validator() {
- actionChars = ACTION_CHARS;
- instChars = INST_CHARS;
- }
-
- /**
- * When Trans is passed in, check for non-standard Action/Inst chars
- *
- * This is an opportunity to change characters, if required.
- *
- * Use for any Object method passed (i.e. role(RoleDAO.Data d) ), to ensure fewer bugs.
- *
- * @param trans
- */
- public Validator(AuthzTrans trans) {
- actionChars = ACTION_CHARS;
- instChars = INST_CHARS;
- }
-
-
- public Validator perm(Result<PermDAO.Data> rpd) {
- if(rpd.notOK()) {
- msg(rpd.details);
- } else {
- perm(rpd.value);
- }
- return this;
- }
-
-
- public Validator 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);
- }
- }
- }
- return this;
- }
-
- public Validator role(Result<RoleDAO.Data> rrd) {
- if(rrd.notOK()) {
- msg(rrd.details);
- } else {
- role(rrd.value);
- }
- return this;
- }
-
- public Validator 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]);
- }
- }
- }
- }
- return this;
- }
-
- public Validator delegate(Organization org, Result<DelegateDAO.Data> rdd) {
- if(rdd.notOK()) {
- msg(rdd.details);
- } else {
- delegate(org, rdd.value);
- }
- return this;
- }
-
- public Validator 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 Validator cred(Organization org, Result<CredDAO.Data> rcd, boolean isNew) {
- if(rcd.notOK()) {
- msg(rcd.details);
- } else {
- cred(org,rcd.value,isNew);
- }
- return this;
- }
-
- public Validator cred(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");
- }
- if(!org.isValidCred(cd.id)) {
- msg("ID [" + cd.id + "] is invalid for a cred");
- }
- 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(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 Validator user(Organization org, String user) {
- if(nob(user,ID_CHARS)) {
- msg("User [",user,"] is invalid.");
- }
- //TODO Change when Multi-Org solution is created
-// if(org instanceof ATT) {
-// if(!user.endsWith("@csp.att.com") &&
-// !org.isValidCred(user))
-// msg("User [",user,"] is not valid ID for Credential in ",org.getRealm());
-// }
- return this;
- }
-
- public Validator ns(Result<Namespace> nsd) {
- notOK(nsd);
- ns(nsd.value.name);
- for(String s : nsd.value.admin) {
- if(nob(s,ID_CHARS)) {
- msg("Admin [" + s + "] is invalid.");
- }
-
- }
- for(String s : nsd.value.owner) {
- if(nob(s,ID_CHARS)) {
- msg("Responsible [" + s + "] is invalid.");
- }
-
- }
- return this;
- }
-
-
- public Validator ns(String ns) {
- if(nob(ns,NAME_CHARS)){
- msg("NS [" + ns + "] is invalid.");
- }
- return this;
- }
-
- public String errs() {
- return msgs.toString();
- }
-
-
- public Validator permType(String type, String ns) {
- // TODO check for correct Splits? Type|Instance|Action ?
- if(nob(type,NAME_CHARS)) {
- msg("Perm Type [" + (ns==null?"":ns+(type.length()==0?"":'.'))+type + "] is invalid.");
- }
- return this;
- }
-
- public Validator permInstance(String instance) {
- // TODO check for correct Splits? Type|Instance|Action ?
- if(nob(instance,instChars)) {
- msg("Perm Instance [" + instance + "] is invalid.");
- }
- return this;
- }
-
- public Validator permAction(String action) {
- // TODO check for correct Splits? Type|Instance|Action ?
- if(nob(action, actionChars)) {
- msg("Perm Action [" + action + "] is invalid.");
- }
- return this;
- }
-
- public Validator role(String role) {
- if(nob(role, NAME_CHARS)) {
- msg("Role [" + role + "] is invalid.");
- }
- return this;
- }
-
- public Validator 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 Validator nullOrBlank(String name, String str) {
- if(str==null) {
- msg(name + " is null.");
- } else if(str.length()==0) {
- msg(name + " is blank.");
- }
- return this;
- }
-
- public Validator 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 Validator nullOrBlank(RoleDAO.Data rd) {
- if(rd==null) {
- msg("Role is null");
- } else {
- nullOrBlank("NS",rd.ns).
- nullOrBlank("Name",rd.name);
- }
- return this;
- }
-
- // nob = Null Or Not match Pattern
- private boolean nob(String str, Pattern p) {
- return str==null || !p.matcher(str).matches();
- }
-
- private void msg(String ... strs) {
- if(msgs==null) {
- msgs=new StringBuilder();
- }
- for(String str : strs) {
- msgs.append(str);
- }
- msgs.append('\n');
- }
-
- public boolean err() {
- return msgs!=null;
- }
-
-
- public Validator notOK(Result<?> res) {
- if(res==null) {
- msgs.append("Result object is blank");
- } else if(res.notOK()) {
- msgs.append(res.getClass().getSimpleName() + " is not OK");
- }
- return this;
- }
-
- public Validator key(String key) {
- if(nob(key,NAME_CHARS)) {
- msg("NS Prop Key [" + key + "] is invalid");
- }
- return this;
- }
-
- public Validator value(String value) {
- if(nob(value,ESSENTIAL_CHARS)) {
- msg("NS Prop value [" + value + "] is invalid");
- }
- return this;
- }
-
-
-}
|