From 0e5efc61b657dba874aacc95ee21c76b95fb2028 Mon Sep 17 00:00:00 2001 From: sg481n Date: Fri, 25 Aug 2017 00:57:25 -0400 Subject: Update aaf client module Remove aaf submodules and update aaf client module. Issue-id: AAF-21 Change-Id: I750ec9e26596652a142b014db94aabd082880130 Signed-off-by: sg481n --- .../main/java/com/att/authz/cadi/DirectAAFLur.java | 169 - .../java/com/att/authz/cadi/DirectAAFUserPass.java | 73 - .../com/att/authz/cadi/DirectCertIdentity.java | 78 - .../java/com/att/authz/facade/AuthzFacade.java | 263 -- .../com/att/authz/facade/AuthzFacadeFactory.java | 56 - .../java/com/att/authz/facade/AuthzFacadeImpl.java | 2564 ------------- .../java/com/att/authz/facade/AuthzFacade_2_0.java | 64 - .../main/java/com/att/authz/service/AuthAPI.java | 330 -- .../att/authz/service/AuthzCassServiceImpl.java | 3972 -------------------- .../java/com/att/authz/service/AuthzService.java | 748 ---- .../src/main/java/com/att/authz/service/Code.java | 45 - .../main/java/com/att/authz/service/MayChange.java | 33 - .../java/com/att/authz/service/api/API_Api.java | 92 - .../com/att/authz/service/api/API_Approval.java | 107 - .../java/com/att/authz/service/api/API_Creds.java | 277 -- .../com/att/authz/service/api/API_Delegate.java | 153 - .../com/att/authz/service/api/API_History.java | 238 -- .../java/com/att/authz/service/api/API_Mgmt.java | 274 -- .../java/com/att/authz/service/api/API_NS.java | 396 -- .../java/com/att/authz/service/api/API_Perms.java | 291 -- .../java/com/att/authz/service/api/API_Roles.java | 313 -- .../java/com/att/authz/service/api/API_User.java | 133 - .../com/att/authz/service/api/API_UserRole.java | 181 - .../java/com/att/authz/service/mapper/Mapper.java | 122 - .../com/att/authz/service/mapper/Mapper_2_0.java | 790 ---- .../att/authz/service/validation/Validator.java | 386 -- 26 files changed, 12148 deletions(-) delete mode 100644 authz-service/src/main/java/com/att/authz/cadi/DirectAAFLur.java delete mode 100644 authz-service/src/main/java/com/att/authz/cadi/DirectAAFUserPass.java delete mode 100644 authz-service/src/main/java/com/att/authz/cadi/DirectCertIdentity.java delete mode 100644 authz-service/src/main/java/com/att/authz/facade/AuthzFacade.java delete mode 100644 authz-service/src/main/java/com/att/authz/facade/AuthzFacadeFactory.java delete mode 100644 authz-service/src/main/java/com/att/authz/facade/AuthzFacadeImpl.java delete mode 100644 authz-service/src/main/java/com/att/authz/facade/AuthzFacade_2_0.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/AuthAPI.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/AuthzCassServiceImpl.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/AuthzService.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/Code.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/MayChange.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_Api.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_Approval.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_Creds.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_Delegate.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_History.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_Mgmt.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_NS.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_Perms.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_Roles.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_User.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/api/API_UserRole.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/mapper/Mapper.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/mapper/Mapper_2_0.java delete mode 100644 authz-service/src/main/java/com/att/authz/service/validation/Validator.java (limited to 'authz-service/src/main/java') diff --git a/authz-service/src/main/java/com/att/authz/cadi/DirectAAFLur.java b/authz-service/src/main/java/com/att/authz/cadi/DirectAAFLur.java deleted file mode 100644 index 984d1d52..00000000 --- a/authz-service/src/main/java/com/att/authz/cadi/DirectAAFLur.java +++ /dev/null @@ -1,169 +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.cadi; - -import static com.att.authz.layer.Result.OK; - -import java.security.Principal; -import java.util.List; - -import com.att.authz.env.AuthzEnv; -import com.att.authz.env.AuthzTrans; -import com.att.authz.layer.Result; -import com.att.cadi.Lur; -import com.att.cadi.Permission; -import com.att.dao.aaf.cass.PermDAO; -import com.att.dao.aaf.cass.PermDAO.Data; -import com.att.dao.aaf.hl.Question; - -public class DirectAAFLur implements Lur { - private final AuthzEnv env; - private final Question question; - - public DirectAAFLur(AuthzEnv env, Question question) { - this.env = env; - this.question = question; - } - - @Override - public boolean fish(Principal bait, Permission pond) { - return fish(env.newTransNoAvg(),bait,pond); - } - - public boolean fish(AuthzTrans trans, Principal bait, Permission pond) { - Result> pdr = question.getPermsByUser(trans, bait.getName(),false); - switch(pdr.status) { - case OK: - for(PermDAO.Data d : pdr.value) { - if(new PermPermission(d).match(pond)) return true; - } - break; - default: - trans.error().log("Can't access Cassandra to fulfill Permission Query: ",pdr.status,"-",pdr.details); - } - return false; - } - - @Override - public void fishAll(Principal bait, List permissions) { - Result> pdr = question.getPermsByUser(env.newTrans(), bait.getName(),false); - switch(pdr.status) { - case OK: - for(PermDAO.Data d : pdr.value) { - permissions.add(new PermPermission(d)); - } - break; - default: - env.error().log("Can't access Cassandra to fulfill Permission Query: ",pdr.status,"-", pdr.details); - } - } - - @Override - public void destroy() { - } - - @Override - public boolean handlesExclusively(Permission pond) { - return false; - } - - /** - * Small Class implementing CADI's Permission with Cassandra Data - * - */ - public static class PermPermission implements Permission { - private PermDAO.Data data; - - public PermPermission(PermDAO.Data d) { - data = d; - } - - public PermPermission(AuthzTrans trans, Question q, String p) { - data = PermDAO.Data.create(trans, q, p); - } - - public PermPermission(String ns, String type, String instance, String action) { - data = new PermDAO.Data(); - data.ns = ns; - data.type = type; - data.instance = instance; - data.action = action; - } - - @Override - public String getKey() { - return data.type; - } - - @Override - public boolean match(Permission p) { - if(p==null)return false; - PermDAO.Data pd; - if(p instanceof DirectAAFLur.PermPermission) { - pd = ((DirectAAFLur.PermPermission)p).data; - if(data.ns.equals(pd.ns)) - if(data.type.equals(pd.type)) - if(data.instance!=null && (data.instance.equals(pd.instance) || "*".equals(data.instance))) - if(data.action!=null && (data.action.equals(pd.action) || "*".equals(data.action))) - return true; - } else{ - String[] lp = p.getKey().split("\\|"); - if(lp.length<3)return false; - if(data.fullType().equals(lp[0])) - if(data.instance!=null && (data.instance.equals(lp[1]) || "*".equals(data.instance))) - if(data.action!=null && (data.action.equals(lp[2]) || "*".equals(data.action))) - return true; - } - return false; - } - - @Override - public String permType() { - return "AAFLUR"; - } - - } - - public String toString() { - return "DirectAAFLur is enabled"; - - } - - @Override - public boolean supports(String userName) { - //TODO - return true; - } - - @Override - public Permission createPerm(String p) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void clear(Principal p, StringBuilder report) { - // TODO Auto-generated method stub - - } -} diff --git a/authz-service/src/main/java/com/att/authz/cadi/DirectAAFUserPass.java b/authz-service/src/main/java/com/att/authz/cadi/DirectAAFUserPass.java deleted file mode 100644 index dedc1a39..00000000 --- a/authz-service/src/main/java/com/att/authz/cadi/DirectAAFUserPass.java +++ /dev/null @@ -1,73 +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.cadi; - -import static com.att.authz.layer.Result.OK; - -import java.util.Date; - -import com.att.authz.env.AuthzEnv; -import com.att.authz.env.AuthzTrans; -import com.att.authz.layer.Result; -import com.att.cadi.CredVal; -import com.att.dao.DAOException; -import com.att.dao.aaf.hl.Question; - -/** - * DirectAAFUserPass is intended to provide password Validation directly from Cassandra Database, and is only - * intended for use in AAF itself. The normal "AAF Taf" objects are, of course, clients. - * - * - */ -public class DirectAAFUserPass implements CredVal { - private final AuthzEnv env; - private final Question question; - - public DirectAAFUserPass(AuthzEnv env, Question question, String appPass) { - this.env = env; - this.question = question; - } - - @Override - public boolean validate(String user, Type type, byte[] pass) { - try { - AuthzTrans trans = env.newTransNoAvg(); - Result result = question.doesUserCredMatch(trans, user, pass); - trans.logAuditTrail(env.info()); - switch(result.status) { - case OK: - return true; - default: - - env.warn().log(user, "failed Password Validation:",result.errorString()); - } - } catch (DAOException e) { - System.out.println(" exception in DirectAAFUserPass class "); - e.printStackTrace(); - env.error().log(e,"Cannot validate User/Pass from Cassandra"); - } - return false; - } - - -} diff --git a/authz-service/src/main/java/com/att/authz/cadi/DirectCertIdentity.java b/authz-service/src/main/java/com/att/authz/cadi/DirectCertIdentity.java deleted file mode 100644 index abc0f10a..00000000 --- a/authz-service/src/main/java/com/att/authz/cadi/DirectCertIdentity.java +++ /dev/null @@ -1,78 +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.cadi; - -import java.nio.ByteBuffer; -import java.security.Principal; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import com.att.authz.env.AuthzTrans; -import com.att.authz.layer.Result; -import com.att.cadi.principal.X509Principal; -import com.att.cadi.taf.cert.CertIdentity; -import com.att.cadi.taf.cert.X509Taf; -import com.att.cssa.rserv.TransFilter; -import com.att.dao.aaf.cached.CachedCertDAO; -import com.att.dao.aaf.cass.CertDAO.Data; - -/** - * Direct view of CertIdentities - * - * Warning: this class is difficult to instantiate. The only service that can use it is AAF itself, and is thus - * entered in the "init" after the CachedCertDAO is created. - * - * - */ -public class DirectCertIdentity implements CertIdentity { - private static CachedCertDAO certDAO; - - @Override - public Principal identity(HttpServletRequest req, X509Certificate cert, byte[] _certBytes) throws CertificateException { - byte[] certBytes = _certBytes; - if(cert==null && certBytes==null) { - return null; - } - if(certBytes==null) { - certBytes = cert.getEncoded(); - } - byte[] fingerprint = X509Taf.getFingerPrint(certBytes); - - AuthzTrans trans = (AuthzTrans) req.getAttribute(TransFilter.TRANS_TAG); - - Result> cresp = certDAO.read(trans, ByteBuffer.wrap(fingerprint)); - if(cresp.isOKhasData()) { - Data cdata = cresp.value.get(0); - return new X509Principal(cdata.id,cert,certBytes); - } - return null; - } - - public static void set(CachedCertDAO ccd) { - certDAO = ccd; - } - -} diff --git a/authz-service/src/main/java/com/att/authz/facade/AuthzFacade.java b/authz-service/src/main/java/com/att/authz/facade/AuthzFacade.java deleted file mode 100644 index 3bed07a4..00000000 --- a/authz-service/src/main/java/com/att/authz/facade/AuthzFacade.java +++ /dev/null @@ -1,263 +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.facade; - -import java.util.Date; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.att.authz.env.AuthzTrans; -import com.att.authz.layer.Result; -import com.att.cssa.rserv.RServlet; -import com.att.dao.aaf.cass.NsType; - -/** - * AuthzFacade - * This layer is responsible for covering the Incoming Messages, be they XML, JSON or just entries on the URL, - * and converting them to data that can be called on the Service Layer. - * - * Upon response, this layer, because it knew the incoming Data Formats (i.e. XML/JSON), the HTTP call types - * are set on "ContentType" on Response. - * - * Finally, we wrap the call in Time Stamps with explanation of what is happing for Audit trails. - * - * - */ -public interface AuthzFacade { - public static final int PERM_DEPEND_424 = -1000; - public static final int ROLE_DEPEND_424 = -1001; - - /* - * Namespaces - */ - public abstract Result requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type); - - public abstract Result getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns); - - public abstract Result getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); - - public abstract Result getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); - - public abstract Result getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); - - public abstract Result getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String pathParam); - - public abstract Result addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); - - public abstract Result delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); - - public abstract Result addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); - - public abstract Result delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); - - public abstract Result updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns); - - // NS Attribs - public abstract Result createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value); - - public abstract Result readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key); - - public abstract Result updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value); - - public abstract Result delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key); - - /* - * Permissions - */ - public abstract Result createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result getPermsByName(AuthzTrans trans, HttpServletResponse resp, - String type, String instance, String action); - - public abstract Result getPermsByUser(AuthzTrans trans, HttpServletResponse response, String user); - - public abstract Result getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest request, HttpServletResponse response, String user); - - public abstract Result getPermsByType(AuthzTrans trans, HttpServletResponse resp, String type); - - public abstract Result getPermsForRole(AuthzTrans trans, HttpServletResponse response, String roleName); - - public abstract Result getPermsByNS(AuthzTrans trans, HttpServletResponse response, String ns); - - public abstract Result renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, - String type, String instance, String action); - - public abstract Result updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result deletePerm(AuthzTrans trans, HttpServletResponse resp, - String perm, String type, String action); - - /* - * Roles - */ - public abstract Result createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse response); - - public abstract Result getRolesByName(AuthzTrans trans,HttpServletResponse resp, String name); - - public abstract Result getRolesByNS(AuthzTrans trans, HttpServletResponse resp, String ns); - - public abstract Result getRolesByNameOnly(AuthzTrans trans, HttpServletResponse resp, String nameOnly); - - public abstract Result getRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user); - - public abstract Result getRolesByPerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action); - - public abstract Result updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result addPermToRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); - - public abstract Result delPermFromRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); - - public abstract Result deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result deleteRole(AuthzTrans trans, HttpServletResponse resp, String role); - - /* - * Users - */ - - public abstract Result getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role); - - public abstract Result getUsersByPermission(AuthzTrans trans, HttpServletResponse resp, - String type, String instance, String action); - - - - /* - * Delegates - */ - public abstract Result createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result deleteDelegate(AuthzTrans trans, String user); - - public abstract Result getDelegatesByUser(AuthzTrans trans, String userName, HttpServletResponse resp); - - public abstract Result getDelegatesByDelegate(AuthzTrans trans, String userName, HttpServletResponse resp); - - /* - * Credentials - */ - public abstract Result createUserCred(AuthzTrans trans, HttpServletRequest req); - - public abstract Result changeUserCred(AuthzTrans trans, HttpServletRequest req); - - public abstract Result extendUserCred(AuthzTrans trans, HttpServletRequest req, String days); - - public abstract Result getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns); - - public abstract Result getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id); - - public abstract Result deleteUserCred(AuthzTrans trans, HttpServletRequest req); - - public abstract Result validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth); - - public abstract Result doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - /* - * Miscellaneous - */ - /** - * Place Standard Messages based on HTTP Code onto Error Data Structure, and write to OutputStream - * Log message - */ - public abstract void error(AuthzTrans trans, HttpServletResponse response, Result result); - - /* - * UserRole - */ - public abstract Result requestUserRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); - - public abstract Result getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role); - - public abstract Result getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role); - - public abstract Result getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user); - - public abstract Result deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role); - - public abstract Result resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req); - - public abstract Result resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req); - - public abstract Result extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, - String role); - - /* - * Approval - */ - public abstract Result updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); - - public abstract Result getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user); - - public abstract Result getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket); - - public abstract Result getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver); - - - /* - * History - */ - public abstract Result getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort); - - public abstract Result getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); - - public abstract Result getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); - - public abstract Result getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); - - /* - * Cache - */ - public abstract Result cacheClear(AuthzTrans trans, String pathParam); - - public abstract Result cacheClear(AuthzTrans trans, String string,String segments); - - public abstract void dbReset(AuthzTrans trans); - - - - /* - * API - */ - public Result getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet); - - public abstract Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String typeCode, boolean optional); - - public abstract Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id); - - - - - -} diff --git a/authz-service/src/main/java/com/att/authz/facade/AuthzFacadeFactory.java b/authz-service/src/main/java/com/att/authz/facade/AuthzFacadeFactory.java deleted file mode 100644 index be4d8e73..00000000 --- a/authz-service/src/main/java/com/att/authz/facade/AuthzFacadeFactory.java +++ /dev/null @@ -1,56 +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.facade; - -import com.att.authz.env.AuthzEnv; -import com.att.authz.env.AuthzTrans; -import com.att.authz.service.AuthzCassServiceImpl; -import com.att.authz.service.mapper.Mapper_2_0; -import com.att.dao.aaf.hl.Question; -import com.att.inno.env.APIException; -import com.att.inno.env.Data; - - -public class AuthzFacadeFactory { - public static AuthzFacade_2_0 v2_0(AuthzEnv env, AuthzTrans trans, Data.TYPE type, Question question) throws APIException { - return new AuthzFacade_2_0(env, - new AuthzCassServiceImpl< - aaf.v2_0.Nss, - aaf.v2_0.Perms, - aaf.v2_0.Pkey, - aaf.v2_0.Roles, - aaf.v2_0.Users, - aaf.v2_0.UserRoles, - aaf.v2_0.Delgs, - aaf.v2_0.Certs, - aaf.v2_0.Keys, - aaf.v2_0.Request, - aaf.v2_0.History, - aaf.v2_0.Error, - aaf.v2_0.Approvals> - (trans,new Mapper_2_0(question),question), - type); - } - - -} diff --git a/authz-service/src/main/java/com/att/authz/facade/AuthzFacadeImpl.java b/authz-service/src/main/java/com/att/authz/facade/AuthzFacadeImpl.java deleted file mode 100644 index 00b288d2..00000000 --- a/authz-service/src/main/java/com/att/authz/facade/AuthzFacadeImpl.java +++ /dev/null @@ -1,2564 +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.facade; - -import static com.att.authz.layer.Result.ERR_ActionNotCompleted; -import static com.att.authz.layer.Result.ERR_Backend; -import static com.att.authz.layer.Result.ERR_BadData; -import static com.att.authz.layer.Result.ERR_ConflictAlreadyExists; -import static com.att.authz.layer.Result.ERR_Denied; -import static com.att.authz.layer.Result.ERR_NotFound; -import static com.att.authz.layer.Result.ERR_NotImplemented; -import static com.att.authz.layer.Result.ERR_Policy; -import static com.att.authz.layer.Result.ERR_Security; -import static com.att.authz.layer.Result.OK; -import static com.att.dao.aaf.cass.Status.ERR_ChoiceNeeded; -import static com.att.dao.aaf.cass.Status.ERR_DelegateNotFound; -import static com.att.dao.aaf.cass.Status.ERR_DependencyExists; -import static com.att.dao.aaf.cass.Status.ERR_FutureNotRequested; -import static com.att.dao.aaf.cass.Status.ERR_InvalidDelegate; -import static com.att.dao.aaf.cass.Status.ERR_NsNotFound; -import static com.att.dao.aaf.cass.Status.ERR_PermissionNotFound; -import static com.att.dao.aaf.cass.Status.ERR_RoleNotFound; -import static com.att.dao.aaf.cass.Status.ERR_UserNotFound; -import static com.att.dao.aaf.cass.Status.ERR_UserRoleNotFound; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.Date; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.att.authz.env.AuthzEnv; -import com.att.authz.env.AuthzTrans; -import com.att.authz.layer.FacadeImpl; -import com.att.authz.layer.Result; -import com.att.authz.service.AuthzCassServiceImpl; -import com.att.authz.service.AuthzService; -import com.att.authz.service.mapper.Mapper; -import com.att.authz.service.mapper.Mapper.API; -import com.att.cadi.aaf.client.Examples; -import com.att.cssa.rserv.RServlet; -import com.att.cssa.rserv.RouteReport; -import com.att.cssa.rserv.doc.ApiDoc; -import com.att.dao.aaf.cass.NsType; -import com.att.dao.aaf.cass.Status; -import com.att.dao.aaf.hl.Question; -import com.att.inno.env.APIException; -import com.att.inno.env.Data; -import com.att.inno.env.Data.TYPE; -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 com.att.rosetta.env.RosettaDF; -import com.att.rosetta.env.RosettaData; - -import aaf.v2_0.Api; - -/** - * AuthzFacade - * - * This Service Facade encapsulates the essence of the API Service can do, and provides - * a single created object for elements such as RosettaDF. - * - * The Responsibilities of this class are to: - * 1) Interact with the Service Implementation (which might be supported by various kinds of Backend Storage) - * 2) Validate incoming data (if applicable) - * 3) Convert the Service response into the right Format, and mark the Content Type - * a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request. - * 4) Log Service info, warnings and exceptions as necessary - * 5) When asked by the API layer, this will create and write Error content to the OutputStream - * - * Note: This Class does NOT set the HTTP Status Code. That is up to the API layer, so that it can be - * clearly coordinated with the API Documentation - * - * - */ -public abstract class AuthzFacadeImpl extends FacadeImpl implements AuthzFacade - { - private static final String FORBIDDEN = "Forbidden"; - private static final String NOT_FOUND = "Not Found"; - private static final String NOT_ACCEPTABLE = "Not Acceptable"; - private static final String GENERAL_SERVICE_ERROR = "General Service Error"; - private static final String NO_DATA = "***No Data***"; - private AuthzService service = null; - private final RosettaDF nssDF; - private final RosettaDF permsDF; - private final RosettaDF roleDF; - private final RosettaDF usersDF; - private final RosettaDF userrolesDF; - private final RosettaDF certsDF; - private final RosettaDF delgDF; - private final RosettaDF permRequestDF; - private final RosettaDF roleRequestDF; - private final RosettaDF userRoleRequestDF; - private final RosettaDF rolePermRequestDF; - private final RosettaDF nsRequestDF; - private final RosettaDF credRequestDF; - private final RosettaDF delgRequestDF; - private final RosettaDF historyDF; - private final RosettaDF keysDF; - - private final RosettaDF errDF; - private final RosettaDF approvalDF; - // Note: Api is not different per Version - private final RosettaDF apiDF; - - - @SuppressWarnings("unchecked") - public AuthzFacadeImpl(AuthzEnv env, AuthzService service, Data.TYPE dataType) throws APIException { - this.service = service; - (nssDF = env.newDataFactory(service.mapper().getClass(API.NSS))).in(dataType).out(dataType); - (permRequestDF = env.newDataFactory(service.mapper().getClass(API.PERM_REQ))).in(dataType).out(dataType); - (permsDF = env.newDataFactory(service.mapper().getClass(API.PERMS))).in(dataType).out(dataType); -// (permKeyDF = env.newDataFactory(service.mapper().getClass(API.PERM_KEY))).in(dataType).out(dataType); - (roleDF = env.newDataFactory(service.mapper().getClass(API.ROLES))).in(dataType).out(dataType); - (roleRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_REQ))).in(dataType).out(dataType); - (usersDF = env.newDataFactory(service.mapper().getClass(API.USERS))).in(dataType).out(dataType); - (userrolesDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLES))).in(dataType).out(dataType); - (certsDF = env.newDataFactory(service.mapper().getClass(API.CERTS))).in(dataType).out(dataType) - .rootMarshal((Marshal) service.mapper().getMarshal(API.CERTS)); - ; - (userRoleRequestDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLE_REQ))).in(dataType).out(dataType); - (rolePermRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_PERM_REQ))).in(dataType).out(dataType); - (nsRequestDF = env.newDataFactory(service.mapper().getClass(API.NS_REQ))).in(dataType).out(dataType); - (credRequestDF = env.newDataFactory(service.mapper().getClass(API.CRED_REQ))).in(dataType).out(dataType); - (delgRequestDF = env.newDataFactory(service.mapper().getClass(API.DELG_REQ))).in(dataType).out(dataType); - (historyDF = env.newDataFactory(service.mapper().getClass(API.HISTORY))).in(dataType).out(dataType); - ( keysDF = env.newDataFactory(service.mapper().getClass(API.KEYS))).in(dataType).out(dataType); - (delgDF = env.newDataFactory(service.mapper().getClass(API.DELGS))).in(dataType).out(dataType); - (approvalDF = env.newDataFactory(service.mapper().getClass(API.APPROVALS))).in(dataType).out(dataType); - (errDF = env.newDataFactory(service.mapper().getClass(API.ERROR))).in(dataType).out(dataType); - (apiDF = env.newDataFactory(Api.class)).in(dataType).out(dataType); - } - - public Mapper mapper() { - return service.mapper(); - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#error(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, int) - * - * Note: Conforms to AT&T TSS RESTful Error Structure - */ - @Override - public void error(AuthzTrans trans, HttpServletResponse response, Result result) { - String msg = result.details==null?"%s":"%s - " + result.details.trim(); - String msgId; - String[] detail; - if(result.variables==null) { - detail = new String[1]; - } else { - int l = result.variables.length; - detail=new String[l+1]; - System.arraycopy(result.variables, 0, detail, 1, l); - } - //int httpstatus; - - switch(result.status) { - case ERR_ActionNotCompleted: - msgId = "SVC1202"; - detail[0] = "Accepted, Action not complete"; - response.setStatus(/*httpstatus=*/202); - break; - - case ERR_Policy: - msgId = "SVC3403"; - detail[0] = FORBIDDEN; - response.setStatus(/*httpstatus=*/403); - break; - case ERR_Security: - msgId = "SVC2403"; - detail[0] = FORBIDDEN; - response.setStatus(/*httpstatus=*/403); - break; - case ERR_Denied: - msgId = "SVC1403"; - detail[0] = FORBIDDEN; - response.setStatus(/*httpstatus=*/403); - break; - // This is still forbidden to directly impact, but can be Requested when passed - // with "request=true" query Param - case ERR_FutureNotRequested: - msgId = "SVC2403"; - detail[0] = msg; - response.setStatus(/*httpstatus=*/403); - break; - - case ERR_NsNotFound: - msgId = "SVC2404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_RoleNotFound: - msgId = "SVC3404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_PermissionNotFound: - msgId = "SVC4404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_UserNotFound: - msgId = "SVC5404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_UserRoleNotFound: - msgId = "SVC6404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_DelegateNotFound: - msgId = "SVC7404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - case ERR_NotFound: - msgId = "SVC1404"; - detail[0] = NOT_FOUND; - response.setStatus(/*httpstatus=*/404); - break; - - case ERR_InvalidDelegate: - msgId="SVC2406"; - detail[0] = NOT_ACCEPTABLE; - response.setStatus(/*httpstatus=*/406); - break; - case ERR_BadData: - msgId="SVC1406"; - detail[0] = NOT_ACCEPTABLE; - response.setStatus(/*httpstatus=*/406); - break; - - case ERR_ConflictAlreadyExists: - msgId = "SVC1409"; - detail[0] = "Conflict Already Exists"; - response.setStatus(/*httpstatus=*/409); - break; - - case ERR_DependencyExists: - msgId = "SVC1424"; - detail[0] = "Failed Dependency"; - response.setStatus(/*httpstatus=*/424); - break; - - case ERR_NotImplemented: - msgId = "SVC1501"; - detail[0] = "Not Implemented"; - response.setStatus(/*httpstatus=*/501); - break; - - case Status.ACC_Future: - msgId = "SVC1202"; - detail[0] = "Accepted for Future, pending Approvals"; - response.setStatus(/*httpstatus=*/202); - break; - case ERR_ChoiceNeeded: - msgId = "SVC1300"; - detail = result.variables; - response.setStatus(/*httpstatus=*/300); - break; - case ERR_Backend: - msgId = "SVC2500"; - detail[0] = GENERAL_SERVICE_ERROR; - response.setStatus(/*httpstatus=*/500); - break; - - default: - msgId = "SVC1500"; - detail[0] = GENERAL_SERVICE_ERROR; - response.setStatus(/*httpstatus=*/500); - break; - } - - try { - StringBuilder holder = new StringBuilder(); - errDF.newData(trans).load( - service.mapper() - .errorFromMessage(holder,msgId,msg,detail)) - .to(response.getOutputStream()); - trans.checkpoint( - holder.toString(), -// String.format("ErrResp [" + msgId + "] " + msg,(Object[])detail), - Env.ALWAYS); - } catch (Exception e) { - trans.error().log(e,"unable to send response for",msg); - } - } - - /////////////////////////// - // Namespace - /////////////////////////// - public static final String CREATE_NS = "createNamespace"; - public static final String ADD_NS_ADMIN = "addNamespaceAdmin"; - public static final String DELETE_NS_ADMIN = "delNamespaceAdmin"; - public static final String ADD_NS_RESPONSIBLE = "addNamespaceResponsible"; - public static final String DELETE_NS_RESPONSIBLE = "delNamespaceResponsible"; - public static final String GET_NS_BY_NAME = "getNamespaceByName"; - public static final String GET_NS_BY_ADMIN = "getNamespaceByAdmin"; - public static final String GET_NS_BY_RESPONSIBLE = "getNamespaceByResponsible"; - public static final String GET_NS_BY_EITHER = "getNamespaceByEither"; - public static final String GET_NS_CHILDREN = "getNamespaceChildren"; - public static final String UPDATE_NS_DESC = "updateNamespaceDescription"; - public static final String DELETE_NS = "deleteNamespace"; - - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#createNS(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type) { - TimeTaken tt = trans.start(CREATE_NS, Env.SUB|Env.ALWAYS); - try { - REQUEST request; - try { - Data rd = nsRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,rd.asString()); - } - request = rd.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,CREATE_NS); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.createNS(trans,request,type); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,CREATE_NS); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#addAdminToNS(com.att.authz.env.AuthzTrans, java.lang.String, java.lang.String) - */ - @Override - public Result addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { - TimeTaken tt = trans.start(ADD_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); - try { - Result rp = service.addAdminNS(trans,ns,id); - switch(rp.status) { - case OK: - //TODO Perms?? - setContentType(resp,nsRequestDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,ADD_NS_ADMIN); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#delAdminFromNS(com.att.authz.env.AuthzTrans, java.lang.String, java.lang.String) - */ - @Override - public Result delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { - TimeTaken tt = trans.start(DELETE_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); - try { - Result rp = service.delAdminNS(trans, ns, id); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_NS_ADMIN); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#addAdminToNS(com.att.authz.env.AuthzTrans, java.lang.String, java.lang.String) - */ - @Override - public Result addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { - TimeTaken tt = trans.start(ADD_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); - try { - Result rp = service.addResponsibleNS(trans,ns,id); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,ADD_NS_RESPONSIBLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#delAdminFromNS(com.att.authz.env.AuthzTrans, java.lang.String, java.lang.String) - */ - @Override - public Result delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { - TimeTaken tt = trans.start(DELETE_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); - try { - Result rp = service.delResponsibleNS(trans, ns, id); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_NS_RESPONSIBLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getNSsByName(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns) { - TimeTaken tt = trans.start(GET_NS_BY_NAME + ' ' + ns, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getNSbyName(trans, ns); - switch(rp.status) { - case OK: - RosettaData data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,nssDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_NS_BY_NAME); - return Result.err(e); - } finally { - tt.done(); - } - } - -// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getNSsByAdmin(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ - TimeTaken tt = trans.start(GET_NS_BY_ADMIN + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getNSbyAdmin(trans, user, full); - switch(rp.status) { - case OK: - RosettaData data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,nssDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_NS_BY_ADMIN); - return Result.err(e); - } finally { - tt.done(); - } - } - -// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ - TimeTaken tt = trans.start(GET_NS_BY_RESPONSIBLE + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getNSbyResponsible(trans, user, full); - switch(rp.status) { - case OK: - RosettaData data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - - setContentType(resp,nssDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_NS_BY_RESPONSIBLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ - TimeTaken tt = trans.start(GET_NS_BY_EITHER + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getNSbyEither(trans, user, full); - - switch(rp.status) { - case OK: - RosettaData data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - - setContentType(resp,nssDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_NS_BY_EITHER); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getNSsByResponsible(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String parent){ - TimeTaken tt = trans.start(GET_NS_CHILDREN + ' ' + parent, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getNSsChildren(trans, parent); - switch(rp.status) { - case OK: - RosettaData data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,nssDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_NS_CHILDREN); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_NS_DESC, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = nsRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,UPDATE_NS_DESC); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.updateNsDescription(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_NS_DESC); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* - * (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#requestNS(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns) { - TimeTaken tt = trans.start(DELETE_NS + ' ' + ns, Env.SUB|Env.ALWAYS); - try { - Result rp = service.deleteNS(trans,ns); - switch(rp.status) { - case OK: - setContentType(resp,nsRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_NS); - return Result.err(e); - } finally { - tt.done(); - } - } - - private final static String NS_CREATE_ATTRIB = "nsCreateAttrib"; - private final static String NS_UPDATE_ATTRIB = "nsUpdateAttrib"; - private final static String READ_NS_BY_ATTRIB = "readNsByAttrib"; - private final static String NS_DELETE_ATTRIB = "nsDeleteAttrib"; - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#createAttribForNS(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) { - TimeTaken tt = trans.start(NS_CREATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS); - try { - Result rp = service.createNsAttrib(trans,ns,key,value); - switch(rp.status) { - case OK: - setContentType(resp, keysDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,NS_CREATE_ATTRIB); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#readAttribForNS(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key) { - TimeTaken tt = trans.start(READ_NS_BY_ATTRIB + ' ' + key, Env.SUB|Env.ALWAYS); - try { - Result rp = service.readNsByAttrib(trans, key); - switch(rp.status) { - case OK: - RosettaData data = keysDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,keysDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,READ_NS_BY_ATTRIB); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#updAttribForNS(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) { - TimeTaken tt = trans.start(NS_UPDATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS); - try { - Result rp = service.updateNsAttrib(trans,ns,key,value); - switch(rp.status) { - case OK: - setContentType(resp, keysDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,NS_UPDATE_ATTRIB); - return Result.err(e); - } finally { - tt.done(); - } - - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#delAttribForNS(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String) - */ - @Override - public Result delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key) { - TimeTaken tt = trans.start(NS_DELETE_ATTRIB + ' ' + ns + ':'+key, Env.SUB|Env.ALWAYS); - try { - Result rp = service.deleteNsAttrib(trans,ns,key); - switch(rp.status) { - case OK: - setContentType(resp, keysDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,NS_DELETE_ATTRIB); - return Result.err(e); - } finally { - tt.done(); - } - } - -// -// PERMISSION -// - public static final String CREATE_PERMISSION = "createPermission"; - public static final String GET_PERMS_BY_TYPE = "getPermsByType"; - public static final String GET_PERMS_BY_NAME = "getPermsByName"; - public static final String GET_PERMISSIONS_BY_USER = "getPermissionsByUser"; - public static final String GET_PERMISSIONS_BY_USER_WITH_QUERY = "getPermissionsByUserWithQuery"; - public static final String GET_PERMISSIONS_BY_ROLE = "getPermissionsByRole"; - public static final String GET_PERMISSIONS_BY_NS = "getPermissionsByNS"; - public static final String UPDATE_PERMISSION = "updatePermission"; - public static final String UPDATE_PERM_DESC = "updatePermissionDescription"; - public static final String SET_PERMISSION_ROLES_TO = "setPermissionRolesTo"; - public static final String DELETE_PERMISSION = "deletePermission"; - - /* - * (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#createOrUpdatePerm(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start( CREATE_PERMISSION, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,CREATE_PERMISSION); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.createPerm(trans,rreq); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,CREATE_PERMISSION); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getChildPerms(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getPermsByType(AuthzTrans trans, HttpServletResponse resp, String perm) { - TimeTaken tt = trans.start(GET_PERMS_BY_TYPE + ' ' + perm, Env.SUB|Env.ALWAYS); - try { - - Result rp = service.getPermsByType(trans, perm); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMS_BY_TYPE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getPermsByName(AuthzTrans trans, HttpServletResponse resp, - String type, String instance, String action) { - - TimeTaken tt = trans.start(GET_PERMS_BY_NAME + ' ' + type - + '|' + instance + '|' + action, Env.SUB|Env.ALWAYS); - try { - - Result rp = service.getPermsByName(trans, type, instance, action); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMS_BY_TYPE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getPermsByUser(AuthzTrans trans, HttpServletResponse resp, String user) { - TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getPermsByUser(trans, user); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMISSIONS_BY_USER, user); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getPermissionByUser(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String user) { - TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER_WITH_QUERY + ' ' + user, Env.SUB|Env.ALWAYS); - try { - PERMS perms; - try { - RosettaData data = permsDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - perms = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,CREATE_PERMISSION); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.getPermsByUser(trans, perms, user); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMISSIONS_BY_USER_WITH_QUERY , user); - return Result.err(e); - } finally { - tt.done(); - } - } - - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getPermissionsForRole(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getPermsForRole(AuthzTrans trans, HttpServletResponse resp, String roleName) { - TimeTaken tt = trans.start(GET_PERMISSIONS_BY_ROLE + ' ' + roleName, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getPermsByRole(trans, roleName); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMISSIONS_BY_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getPermsByNS(AuthzTrans trans,HttpServletResponse resp,String ns) { - TimeTaken tt = trans.start(GET_PERMISSIONS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getPermsByNS(trans, ns); - switch(rp.status) { - case OK: - RosettaData data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_PERMISSIONS_BY_NS); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* - * (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#createOrUpdatePerm(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, - String origType, String origInstance, String origAction) { - String cmdDescription = UPDATE_PERMISSION; - TimeTaken tt = trans.start( cmdDescription + ' ' + origType + ' ' + origInstance + ' ' + origAction, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,cmdDescription); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.renamePerm(trans,rreq, origType, origInstance, origAction); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,cmdDescription); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_PERM_DESC, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,UPDATE_PERM_DESC); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.updatePermDescription(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,permRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_PERM_DESC); - return Result.err(e); - } finally { - tt.done(); - } - } - - - @Override - public Result resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(SET_PERMISSION_ROLES_TO, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN, SET_PERMISSION_ROLES_TO); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.resetPermRoles(trans, rreq); - - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,SET_PERMISSION_ROLES_TO); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DELETE_PERMISSION, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,DELETE_PERMISSION); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - - Result rp = service.deletePerm(trans,rreq); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_PERMISSION); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deletePerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action) { - TimeTaken tt = trans.start(DELETE_PERMISSION + type + ' ' + instance + ' ' + action, Env.SUB|Env.ALWAYS); - try { - Result rp = service.deletePerm(trans,type,instance,action); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_PERMISSION); - return Result.err(e); - } finally { - tt.done(); - } - } - - public static final String CREATE_ROLE = "createRole"; - public static final String GET_ROLES_BY_USER = "getRolesByUser"; - public static final String GET_ROLES_BY_NS = "getRolesByNS"; - public static final String GET_ROLES_BY_NAME_ONLY = "getRolesByNameOnly"; - public static final String GET_ROLES_BY_NAME = "getRolesByName"; - public static final String GET_ROLES_BY_PERM = "getRolesByPerm"; - public static final String UPDATE_ROLE_DESC = "updateRoleDescription"; - public static final String ADD_PERM_TO_ROLE = "addPermissionToRole"; - public static final String DELETE_PERM_FROM_ROLE = "deletePermissionFromRole"; - public static final String UPDATE_MGTPERM_ROLE = "updateMgtPermRole"; - public static final String DELETE_ROLE = "deleteRole"; - public static final String GET_CERT_BY_ID = "getCertByID"; - - @Override - public Result createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(CREATE_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = roleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,CREATE_ROLE); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.createRole(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,roleRequestDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,CREATE_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getRolesByName(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getRolesByName(AuthzTrans trans, HttpServletResponse resp, String role) { - TimeTaken tt = trans.start(GET_ROLES_BY_NAME + ' ' + role, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getRolesByName(trans, role); - switch(rp.status) { - case OK: - RosettaData data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,roleDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_ROLES_BY_NAME); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getRolesByUser(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getRolesByUser(AuthzTrans trans,HttpServletResponse resp, String user) { - TimeTaken tt = trans.start(GET_ROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getRolesByUser(trans, user); - switch(rp.status) { - case OK: - RosettaData data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,roleDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_ROLES_BY_USER, user); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getRolesByUser(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getRolesByNS(AuthzTrans trans,HttpServletResponse resp, String ns) { - TimeTaken tt = trans.start(GET_ROLES_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getRolesByNS(trans, ns); - switch(rp.status) { - case OK: - if(!rp.isEmpty()) { - RosettaData data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - } else { - Question.logEncryptTrace(trans, NO_DATA); - } - setContentType(resp,roleDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_ROLES_BY_NS); - return Result.err(e); - } finally { - tt.done(); - } - } - - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getRolesByNameOnly(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getRolesByNameOnly(AuthzTrans trans,HttpServletResponse resp, String nameOnly) { - TimeTaken tt = trans.start(GET_ROLES_BY_NAME_ONLY + ' ' + nameOnly, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getRolesByNameOnly(trans, nameOnly); - switch(rp.status) { - case OK: - if(!rp.isEmpty()) { - RosettaData data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - } else { - Question.logEncryptTrace(trans, NO_DATA); - } - setContentType(resp,roleDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_ROLES_BY_NAME_ONLY); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getRolesByUser(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getRolesByPerm(AuthzTrans trans,HttpServletResponse resp, String type, String instance, String action) { - TimeTaken tt = trans.start(GET_ROLES_BY_PERM + type +' '+instance+' '+action, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getRolesByPerm(trans, type,instance,action); - switch(rp.status) { - case OK: - RosettaData data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,roleDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_ROLES_BY_PERM); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* - * (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#updateDescription(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_ROLE_DESC, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = roleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,UPDATE_ROLE_DESC); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.updateRoleDescription(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,roleRequestDF.getOutType()); - return Result.ok(); - default: - return rp; - } - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_ROLE_DESC); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result addPermToRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(ADD_PERM_TO_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,ADD_PERM_TO_ROLE); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.addPermToRole(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,ADD_PERM_TO_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result delPermFromRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DELETE_PERM_FROM_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,DELETE_PERM_FROM_ROLE); - return Result.err(Status.ERR_BadData,"Invalid Input"); - - } - Result rp = service.delPermFromRole(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - resp.getOutputStream().println(); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_PERM_FROM_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteRole(AuthzTrans trans, HttpServletResponse resp, String role) { - TimeTaken tt = trans.start(DELETE_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); - try { - Result rp = service.deleteRole(trans, role); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DELETE_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = roleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN,CREATE_ROLE); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.deleteRole(trans, rreq); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - public static final String CREATE_CRED = "createUserCred"; - private static final String GET_CREDS_BY_NS = "getCredsByNS"; - private static final String GET_CREDS_BY_ID = "getCredsByID"; - public static final String UPDATE_CRED = "updateUserCred"; - public static final String EXTEND_CRED = "extendUserCred"; - public static final String DELETE_CRED = "deleteUserCred"; - public static final String DOES_CRED_MATCH = "doesCredMatch"; - public static final String VALIDATE_BASIC_AUTH = "validateBasicAuth"; - - - - @Override - /** - * Create Credential - * - */ - public Result createUserCred(AuthzTrans trans, HttpServletRequest req) { - TimeTaken tt = trans.start(CREATE_CRED, Env.SUB|Env.ALWAYS); - try { - RosettaData data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - return service.createUserCred(trans, data.asObject()); - } catch(APIException e) { - trans.error().log(e,"Bad Input data"); - return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); - } catch (Exception e) { - trans.error().log(e,IN,CREATE_CRED); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result changeUserCred(AuthzTrans trans, HttpServletRequest req) { - TimeTaken tt = trans.start(UPDATE_CRED, Env.SUB|Env.ALWAYS); - try { - RosettaData data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.changeUserCred(trans, data.asObject()); - } catch(APIException e) { - trans.error().log(e,"Bad Input data"); - return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_CRED); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#extendUserCred(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, int) - */ - @Override - public Result extendUserCred(AuthzTrans trans, HttpServletRequest req, String days) { - TimeTaken tt = trans.start(EXTEND_CRED, Env.SUB|Env.ALWAYS); - try { - RosettaData data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.extendUserCred(trans, data.asObject(), days); - } catch(APIException e) { - trans.error().log(e,"Bad Input data"); - return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); - } catch (Exception e) { - trans.error().log(e,IN,EXTEND_CRED); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns) { - TimeTaken tt = trans.start(GET_CREDS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); - - try { - Result ru = service.getCredsByNS(trans,ns); - switch(ru.status) { - case OK: - RosettaData data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans,trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_CREDS_BY_NS); - return Result.err(e); - } finally { - tt.done(); - } - - } - - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getCredsByID(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id) { - TimeTaken tt = trans.start(GET_CREDS_BY_ID + ' ' + id, Env.SUB|Env.ALWAYS); - - try { - Result ru = service.getCredsByID(trans,id); - switch(ru.status) { - case OK: - RosettaData data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_CREDS_BY_ID); - return Result.err(e); - } finally { - tt.done(); - } - - } - - @Override - public Result deleteUserCred(AuthzTrans trans, HttpServletRequest req) { - TimeTaken tt = trans.start(DELETE_CRED, Env.SUB|Env.ALWAYS); - try { - RosettaData data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.deleteUserCred(trans, data.asObject()); - } catch(APIException e) { - trans.error().log(e,"Bad Input data"); - return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); - } catch (Exception e) { - trans.error().log(e,IN,DELETE_CRED); - return Result.err(e); - } finally { - tt.done(); - } - } - - - @Override - public Result doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DOES_CRED_MATCH, Env.SUB|Env.ALWAYS); - try { - RosettaData data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.doesCredentialMatch(trans, data.asObject()); - } catch(APIException e) { - trans.error().log(e,"Bad Input data"); - return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); - } catch (IOException e) { - trans.error().log(e,IN,DOES_CRED_MATCH); - return Result.err(e); - } finally { - tt.done(); - } - } - - - @Override - public Result validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth) { - TimeTaken tt = trans.start(VALIDATE_BASIC_AUTH, Env.SUB|Env.ALWAYS); - try { - Result result = service.validateBasicAuth(trans,basicAuth); - switch(result.status){ - case OK: - resp.getOutputStream().write(Chrono.utcStamp(result.value).getBytes()); - return Result.ok(); - } - return Result.err(result); - } catch (Exception e) { - trans.error().log(e,IN,VALIDATE_BASIC_AUTH); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getCertInfoByID(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id) { - TimeTaken tt = trans.start(GET_CERT_BY_ID, Env.SUB|Env.ALWAYS); - try { - Result rci = service.getCertInfoByID(trans,req,id); - - switch(rci.status) { - case OK: - if(Question.willSpecialLog(trans, trans.user())) { - RosettaData data = certsDF.newData(trans).load(rci.value); - Question.logEncryptTrace(trans,data.asString()); - data.to(resp.getOutputStream()); - } else { - certsDF.direct(trans, rci.value, resp.getOutputStream()); - } - setContentType(resp,certsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rci); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_CERT_BY_ID); - return Result.err(e); - } finally { - tt.done(); - } - } - - public static final String CREATE_DELEGATE = "createDelegate"; - public static final String UPDATE_DELEGATE = "updateDelegate"; - public static final String DELETE_DELEGATE = "deleteDelegate"; - public static final String GET_DELEGATE_USER = "getDelegatesByUser"; - public static final String GET_DELEGATE_DELG = "getDelegatesByDelegate"; - - @Override - public Result createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(CREATE_DELEGATE, Env.SUB|Env.ALWAYS); - try { - Data data = delgRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.createDelegate(trans, data.asObject()); - } catch (Exception e) { - trans.error().log(e,IN,CREATE_DELEGATE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_DELEGATE, Env.SUB|Env.ALWAYS); - try { - Data data = delgRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.updateDelegate(trans, data.asObject()); - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_DELEGATE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(DELETE_DELEGATE, Env.SUB|Env.ALWAYS); - try { - Data data = delgRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - return service.deleteDelegate(trans, data.asObject()); - } catch (Exception e) { - trans.error().log(e,IN,DELETE_DELEGATE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteDelegate(AuthzTrans trans, String userName) { - TimeTaken tt = trans.start(DELETE_DELEGATE + ' ' + userName, Env.SUB|Env.ALWAYS); - try { - return service.deleteDelegate(trans, userName); - } catch (Exception e) { - trans.error().log(e,IN,DELETE_DELEGATE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getDelegatesByUser(AuthzTrans trans, String user, HttpServletResponse resp) { - TimeTaken tt = trans.start(GET_DELEGATE_USER, Env.SUB|Env.ALWAYS); - try { - Result rd = service.getDelegatesByUser(trans, user); - - switch(rd.status) { - case OK: - RosettaData data = delgDF.newData(trans).load(rd.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,delgDF.getOutType()); - return Result.ok(); - default: - return Result.err(rd); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_DELEGATE_USER); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getDelegatesByDelegate(AuthzTrans trans, String delegate, HttpServletResponse resp) { - TimeTaken tt = trans.start(GET_DELEGATE_DELG, Env.SUB|Env.ALWAYS); - try { - Result rd = service.getDelegatesByDelegate(trans, delegate); - switch(rd.status) { - case OK: - RosettaData data = delgDF.newData(trans).load(rd.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - setContentType(resp,delgDF.getOutType()); - return Result.ok(); - default: - return Result.err(rd); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_DELEGATE_DELG); - return Result.err(e); - } finally { - tt.done(); - } - } - - private static final String REQUEST_USER_ROLE = "createUserRole"; - private static final String GET_USERROLES = "getUserRoles"; - private static final String GET_USERROLES_BY_ROLE = "getUserRolesByRole"; - private static final String GET_USERROLES_BY_USER = "getUserRolesByUser"; - private static final String SET_ROLES_FOR_USER = "setRolesForUser"; - private static final String SET_USERS_FOR_ROLE = "setUsersForRole"; - private static final String EXTEND_USER_ROLE = "extendUserRole"; - private static final String DELETE_USER_ROLE = "deleteUserRole"; - @Override - public Result requestUserRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(REQUEST_USER_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST request; - try { - Data data = userRoleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - request = data.asObject(); - } catch(APIException e) { - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.createUserRole(trans,request); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,REQUEST_USER_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) { - TimeTaken tt = trans.start(GET_USERROLES + ' ' + user + '|' + role, Env.SUB|Env.ALWAYS); - try { - Result ru = service.getUserInRole(trans,user,role); - switch(ru.status) { - case OK: - RosettaData data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_USERROLES); - return Result.err(e); - } finally { - tt.done(); - } - - } - - @Override - public Result getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user) { - TimeTaken tt = trans.start(GET_USERROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result ru = service.getUserRolesByUser(trans,user); - switch(ru.status) { - case OK: - RosettaData data = userrolesDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_USERROLES_BY_USER); - return Result.err(e); - } finally { - tt.done(); - } - - } - - @Override - public Result getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role) { - TimeTaken tt = trans.start(GET_USERROLES_BY_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); - try { - Result ru = service.getUserRolesByRole(trans,role); - switch(ru.status) { - case OK: - RosettaData data = userrolesDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_USERROLES_BY_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - - } - - - @Override - public Result resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) { - TimeTaken tt = trans.start(SET_USERS_FOR_ROLE, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = userRoleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN, SET_USERS_FOR_ROLE); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.resetUsersForRole(trans, rreq); - - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,SET_USERS_FOR_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - - } - - @Override - public Result resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) { - TimeTaken tt = trans.start(SET_ROLES_FOR_USER, Env.SUB|Env.ALWAYS); - try { - REQUEST rreq; - try { - RosettaData data = userRoleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - rreq = data.asObject(); - } catch(APIException e) { - trans.error().log("Invalid Input",IN, SET_ROLES_FOR_USER); - return Result.err(Status.ERR_BadData,"Invalid Input"); - } - - Result rp = service.resetRolesForUser(trans, rreq); - - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,SET_ROLES_FOR_USER); - return Result.err(e); - } finally { - tt.done(); - } - - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#extendUserRoleExpiration(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String) - */ - @Override - public Result extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, String role) { - TimeTaken tt = trans.start(EXTEND_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS); - try { - return service.extendUserRole(trans,user,role); - } catch (Exception e) { - trans.error().log(e,IN,EXTEND_USER_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) { - TimeTaken tt = trans.start(DELETE_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS); - try { - Result rp = service.deleteUserRole(trans,user,role); - switch(rp.status) { - case OK: - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,DELETE_USER_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - private static final String UPDATE_APPROVAL = "updateApproval"; - private static final String GET_APPROVALS_BY_USER = "getApprovalsByUser."; - private static final String GET_APPROVALS_BY_TICKET = "getApprovalsByTicket."; - private static final String GET_APPROVALS_BY_APPROVER = "getApprovalsByApprover."; - - @Override - public Result updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { - TimeTaken tt = trans.start(UPDATE_APPROVAL, Env.SUB|Env.ALWAYS); - try { - Data data = approvalDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - Result rp = service.updateApproval(trans, data.asObject()); - - switch(rp.status) { - case OK: - setContentType(resp,approvalDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,UPDATE_APPROVAL); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user) { - TimeTaken tt = trans.start(GET_APPROVALS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getApprovalsByUser(trans, user); - switch(rp.status) { - case OK: - RosettaData data = approvalDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - data.to(resp.getOutputStream()); - - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_APPROVALS_BY_USER, user); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver) { - TimeTaken tt = trans.start(GET_APPROVALS_BY_APPROVER + ' ' + approver, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getApprovalsByApprover(trans, approver); - switch(rp.status) { - case OK: - RosettaData data = approvalDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_APPROVALS_BY_APPROVER,approver); - return Result.err(e); - } finally { - tt.done(); - } - } - - @Override - public Result getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket) { - TimeTaken tt = trans.start(GET_APPROVALS_BY_TICKET, Env.SUB|Env.ALWAYS); - try { - Result rp = service.getApprovalsByTicket(trans, ticket); - switch(rp.status) { - case OK: - RosettaData data = approvalDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,permsDF.getOutType()); - return Result.ok(); - default: - return Result.err(rp); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_APPROVALS_BY_TICKET); - return Result.err(e); - } finally { - tt.done(); - } - } - - - - public static final String GET_USERS_PERMISSION = "getUsersByPermission"; - public static final String GET_USERS_ROLE = "getUsersByRole"; - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getUsersByRole(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role) { - TimeTaken tt = trans.start(GET_USERS_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); - try { - Result ru = service.getUsersByRole(trans,role); - switch(ru.status) { - case OK: - RosettaData data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_USERS_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getUsersByPermission(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public Result getUsersByPermission(AuthzTrans trans, HttpServletResponse resp, - String type, String instance, String action) { - TimeTaken tt = trans.start(GET_USERS_PERMISSION + ' ' + type + ' ' + instance + ' ' +action, Env.SUB|Env.ALWAYS); - try { - Result ru = service.getUsersByPermission(trans,type,instance,action); - switch(ru.status) { - case OK: - RosettaData data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,usersDF.getOutType()); - return Result.ok(); - default: - return Result.err(ru); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_USERS_PERMISSION); - return Result.err(e); - } finally { - tt.done(); - } - } - - - public static final String GET_HISTORY_USER = "getHistoryByUser"; - public static final String GET_HISTORY_ROLE = "getHistoryByRole"; - public static final String GET_HISTORY_PERM = "getHistoryByPerm"; - public static final String GET_HISTORY_NS = "getHistoryByNS"; - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getHistoryByUser(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public Result getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort) { - StringBuilder sb = new StringBuilder(); - sb.append(GET_HISTORY_USER); - sb.append(' '); - sb.append(user); - sb.append(" for "); - boolean first = true; - for(int i : yyyymm) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append(i); - } - TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); - - try { - Result rh = service.getHistoryByUser(trans,user,yyyymm,sort); - switch(rh.status) { - case OK: - RosettaData data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,historyDF.getOutType()); - return Result.ok(); - default: - return Result.err(rh); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_HISTORY_USER); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getHistoryByRole(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) - */ - @Override - public Result getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String role, int[] yyyymm, final int sort) { - StringBuilder sb = new StringBuilder(); - sb.append(GET_HISTORY_ROLE); - sb.append(' '); - sb.append(role); - sb.append(" for "); - boolean first = true; - for(int i : yyyymm) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append(i); - } - TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); - try { - Result rh = service.getHistoryByRole(trans,role,yyyymm,sort); - switch(rh.status) { - case OK: - RosettaData data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,historyDF.getOutType()); - return Result.ok(); - default: - return Result.err(rh); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_HISTORY_ROLE); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getHistoryByNS(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) - */ - @Override - public Result getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String ns, int[] yyyymm, final int sort) { - StringBuilder sb = new StringBuilder(); - sb.append(GET_HISTORY_NS); - sb.append(' '); - sb.append(ns); - sb.append(" for "); - boolean first = true; - for(int i : yyyymm) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append(i); - } - TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); - try { - Result rh = service.getHistoryByNS(trans,ns,yyyymm,sort); - switch(rh.status) { - case OK: - RosettaData data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,historyDF.getOutType()); - return Result.ok(); - default: - return Result.err(rh); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_HISTORY_NS); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getHistoryByPerm(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) - */ - @Override - public Result getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String perm, int[] yyyymm, final int sort) { - StringBuilder sb = new StringBuilder(); - sb.append(GET_HISTORY_PERM); - sb.append(' '); - sb.append(perm); - sb.append(" for "); - boolean first = true; - for(int i : yyyymm) { - if(first) { - first = false; - } else { - sb.append(','); - } - sb.append(i); - } - TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); - try { - Result rh = service.getHistoryByPerm(trans,perm,yyyymm,sort); - switch(rh.status) { - case OK: - RosettaData data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,historyDF.getOutType()); - return Result.ok(); - default: - return Result.err(rh); - } - } catch (Exception e) { - trans.error().log(e,IN,GET_HISTORY_PERM); - return Result.err(e); - } finally { - tt.done(); - } - } - - public final static String CACHE_CLEAR = "cacheClear "; -// public final static String CACHE_VALIDATE = "validateCache"; - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#cacheClear(com.att.authz.env.AuthzTrans, java.lang.String) - */ - @Override - public Result cacheClear(AuthzTrans trans, String cname) { - TimeTaken tt = trans.start(CACHE_CLEAR + cname, Env.SUB|Env.ALWAYS); - try { - return service.cacheClear(trans,cname); - } catch (Exception e) { - trans.error().log(e,IN,CACHE_CLEAR); - return Result.err(e); - } finally { - tt.done(); - } - } - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#cacheClear(com.att.authz.env.AuthzTrans, java.lang.String, java.lang.Integer) - */ - @Override - public Result cacheClear(AuthzTrans trans, String cname, String segments) { - TimeTaken tt = trans.start(CACHE_CLEAR + cname + ", segments[" + segments + ']', Env.SUB|Env.ALWAYS); - try { - String[] segs = segments.split("\\s*,\\s*"); - int isegs[] = new int[segs.length]; - for(int i=0;i getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet) { - TimeTaken tt = trans.start(API_REPORT, Env.SUB); - try { - Api api = new Api(); - Api.Route ar; - Method[] meths = AuthzCassServiceImpl.class.getDeclaredMethods(); - for(RouteReport rr : rservlet.routeReport()) { - api.getRoute().add(ar = new Api.Route()); - ar.setMeth(rr.meth.name()); - ar.setPath(rr.path); - ar.setDesc(rr.desc); - ar.getContentType().addAll(rr.contextTypes); - for(Method m : meths) { - ApiDoc ad; - if((ad = m.getAnnotation(ApiDoc.class))!=null && - rr.meth.equals(ad.method()) && - rr.path.equals(ad.path())) { - for(String param : ad.params()) { - ar.getParam().add(param); - } - for(String text : ad.text()) { - ar.getComments().add(text); - } - ar.setExpected(ad.expectedCode()); - for(int ec : ad.errorCodes()) { - ar.getExplicitErr().add(ec); - } - } - } - } - RosettaData data = apiDF.newData(trans).load(api); - if(Question.willSpecialLog(trans, trans.user())) { - Question.logEncryptTrace(trans,data.asString()); - } - - data.to(resp.getOutputStream()); - setContentType(resp,apiDF.getOutType()); - return Result.ok(); - - } catch (Exception e) { - trans.error().log(e,IN,API_REPORT); - return Result.err(e); - } finally { - tt.done(); - } - } - - - public final static String API_EXAMPLE = "apiExample"; - - /* (non-Javadoc) - * @see com.att.authz.facade.AuthzFacade#getAPIExample(com.att.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) - */ - @Override - public Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) { - TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB); - try { - String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional); - resp.getOutputStream().print(content); - setContentType(resp,content.contains(" -{ - public AuthzFacade_2_0(AuthzEnv env, - AuthzService service, - Data.TYPE type) throws APIException { - super(env, service, type); - } -} 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 slist = new ArrayList(); - 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 edlist = EnumSet.of( - RequestDispatcherType.REQUEST, - RequestDispatcherType.FORWARD, - RequestDispatcherType.ASYNC - ); - - List flist = new ArrayList(); - - // 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 ss; - -// InetAddress ip = InetAddress.getByName(dme2svr.getHostname()); - SecurityInfoC si = new SecurityInfoC(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 - * @param - * @param - * @param - * @param - * @param - * @param - * @param - * @param - * @param - */ -public class AuthzCassServiceImpl - implements AuthzService { - - private Mapper mapper; - @Override - public Mapper 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 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: ", - "
  • name - What you want to call this Namespace
  • ", - "
  • 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
  • ", - "
  • admin(s) - Person(s) who are allowed to make changes on the namespace, ", - "including creating Roles, Permissions and Credentials. Separate multiple ", - "identities with commas
", - "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 createNS(final AuthzTrans trans, REQUEST from, NsType type) { - final Result 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 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 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 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> 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 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 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 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 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 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> 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 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> 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> 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 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> 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 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> 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 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> 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 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> 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 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> 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> loadNamepace(AuthzTrans trans, String user, String endsWith, boolean full) { - Result> urd = ques.userRoleDAO.readByUser(trans, user); - if(urd.notOKorIsEmpty()) { - return Result.err(urd); - } - Map lm = new HashMap(); - Map other = full || endsWith==null?null:new TreeMap(); - for(UserRoleDAO.Data urdd : urd.value) { - if(full) { - if(endsWith==null || urdd.role.endsWith(endsWith)) { - RoleDAO.Data rd = RoleDAO.Data.decode(urdd); - Result 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> 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 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(); - namespace.owner=new ArrayList(); - } - 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 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> 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 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 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 lm = new HashSet(); - Result> 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> 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 updateNsDescription(AuthzTrans trans, REQUEST from) { - final Result 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> 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 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", - "

WARNING: Using force will delete all credentials attached to this namespace. Use with care.

" - + "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 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:", - "
  • type - a Namespace qualified identifier specifying what kind of resource " - + "is being protected
  • ", - "
  • instance - a key, possibly multi-dimensional, that identifies a specific " - + " instance of the type
  • ", - "
  • action - what kind of action is allowed
", - "Note: instance and action can be an *" - } - ) - @Override - public Result createPerm(final AuthzTrans trans,REQUEST rreq) { - final Result 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 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 nsd; - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.mayUser(trans, trans.user(), newPd.value, Access.write); - } - return nsd; - } - }); - Result> nsr = ques.nsDAO.read(trans, newPd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - switch(fd.status) { - case OK: - Result> 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 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> 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 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 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> 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", - "

'user' must be expressed as full identity (ex: id@full.domain.com)

"} - ) - @Override - public Result 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> 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", - "

'user' must be expressed as full identity (ex: id@full.domain.com)

", - "", - "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:", - " .access|:[:key]|", - " 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 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> 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> in = mapper.perms(trans, perms); - if(in.isOKhasData()) { - List 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 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 rrdd = RoleDAO.Data.decode(trans, ques,role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - - Result r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); - if(r.notOK()) { - return Result.err(r); - } - - PERMS perms = mapper.newInstance(API.PERMS); - - Result> 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 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 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> 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 renamePerm(final AuthzTrans trans,REQUEST rreq, String origType, String origInstance, String origAction) { - final Result 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 nss = ques.deriveNsSplit(trans, origType); - Result> 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. " + - " 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 origRoles = origPd.roles(false); - if (!origRoles.isEmpty()) { - Set roles = newPd.value.roles(true); - for (String role : origPd.roles) { - roles.add(role); - } - } - - newPd.value.description = origPd.description; - - Result 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 updatePermDescription(AuthzTrans trans, REQUEST from) { - final Result 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> nsr = ques.nsDAO.read(trans, pd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - Result 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 resetPermRoles(final AuthzTrans trans, REQUEST rreq) { - final Result 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 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> 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 updtRoles = new HashSet(); - Result 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 rv = null; - - for(PermDAO.Data curr : rcurr.value) { - Set 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 key = RoleDAO.Data.decode(trans, ques, role); - if(key.isOKhasData()) { - Result> 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 key = RoleDAO.Data.decode(trans, ques, role); - if(key.isOKhasData()) { - Result> 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.", - "

WARNING: Using force will ungrant this permission from all roles. Use with care.

" } - ) - @Override - public Result deletePerm(final AuthzTrans trans, REQUEST from) { - Result 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 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 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> nsr = ques.nsDAO.read(trans, perm.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - Result> 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", - "

WARNING: Using force will ungrant this permission from all roles. Use with care.

"} - ) - @Override - public Result 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 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:", - "
  • org.osaaf - A Possible root Namespace for maintaining AAF
  • ", - "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:", - "
    • Must start with valid Namespace name, terminated by . (dot/period)
    • ", - "
    • Allowed Characters are a-zA-Z0-9._-
    • ", - "
    • role names are Case Sensitive
    ", - "The right questions to ask for defining and populating a Role in AAF, therefore, are:", - "
    • 'What Job Function does this represent?'
    • ", - "
    • 'Does this person perform this Job Function?'
    " } - ) - - @Override - public Result createRole(final AuthzTrans trans, REQUEST from) { - final Result 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 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 nsd; - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.mayUser(trans, trans.user(), role, Access.write); - } - return nsd; - } - }); - - Result> nsr = ques.nsDAO.read(trans, rd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - switch(fd.status) { - case OK: - Result> 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 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 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 rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.isOKhasData()) { - Result 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> 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 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> rlrd; - Result> 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 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 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> 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 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> 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:", - "
    • type - a Namespace qualified identifier specifying what kind of resource " - + "is being protected
    • ", - "
    • instance - a key, possibly multi-dimensional, that identifies a specific " - + " instance of the type
    • ", - "
    • action - what kind of action is allowed
    ", - "Notes: instance and action can be an *", - " You must have permission to see any given role" - } - ) - - @Override - public Result 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 = 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> pdlr = ques.permDAO.read(trans, pdd); - if(pdlr.isOK())for(PermDAO.Data pd : pdlr.value) { - Result> rlrd; - for(String r : pd.roles) { - Result 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 updateRoleDescription(AuthzTrans trans, REQUEST from) { - final Result 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> nsr = ques.nsDAO.read(trans, rd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - Result 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:", - "
    • type - a Namespace qualified identifier specifying what kind of resource " - + "is being protected
    • ", - "
    • instance - a key, possibly multi-dimensional, that identifies a specific " - + " instance of the type
    • ", - "
    • action - what kind of action is allowed
    ", - "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 addPermToRole(final AuthzTrans trans, REQUEST rreq) { - // Translate Request into Perm and Role Objects - final Result rpd = mapper.permFromRPRequest(trans, rreq); - if(rpd.notOKorIsEmpty()) { - return Result.err(rpd); - } - final Result 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> 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> 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 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 nsd; - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.mayUser(trans, trans.user(), rpd.value, Access.write); - } - return nsd; - } - }); - Result> nsr = ques.nsDAO.read(trans, rpd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - switch(fd.status) { - case OK: - Result> 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 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 delPermFromRole(final AuthzTrans trans, REQUEST rreq) { - final Result updt = mapper.permFromRPRequest(trans, rreq); - if(updt.notOKorIsEmpty()) { - return Result.err(updt); - } - final Result 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> 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 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 nsd; - @Override - public Result mayChange() { - if(nsd==null) { - nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write); - } - return nsd; - } - }); - Result> nsr = ques.nsDAO.read(trans, updt.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - switch(fd.status) { - case OK: - Result> 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 deleteRole(AuthzTrans trans, String role) { - Result 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.", - "

    WARNING: Using force will remove all users and permission from this role. Use with care.

    "} - ) - - @Override - public Result deleteRole(final AuthzTrans trans, REQUEST from) { - final Result 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 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 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> nsr = ques.nsDAO.read(trans, rd.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - Result> 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 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 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:", - "
    • 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
    • ", - "
    • password - Company Policy Compliant Password
    ", - "Note: AAF does support multiple credentials with the same ID.", - "Check with your organization if you have this implemented." - } - ) - @Override - public Result createUserCred(final AuthzTrans trans, REQUEST from) { - final String cmdDescription = ("Create User Credential"); - TimeTaken tt = trans.start(cmdDescription, Env.SUB); - - try { - Result 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> 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> 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 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> 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> 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"); - } - Resultudr = 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 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 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> 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 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 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> 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 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> 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 changeUserCred(final AuthzTrans trans, REQUEST from) { - final String cmdDescription = "Update User Credential"; - TimeTaken tt = trans.start(cmdDescription, Env.SUB); - try { - Result 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> 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 ri = selectEntryIfMultiple((CredRequest)from, rlcd.value); - if(ri.notOK()) { - return Result.err(ri); - } - int entry = ri.value; - - - final CredDAO.Data cred = rcred.value; - - Result 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> nsr = ques.nsDAO.read(trans, rcred.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - switch(fd.status) { - case OK: - Result> 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: - Resultudr = 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 selectEntryIfMultiple(final CredRequest cr, List 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 extendUserCred(final AuthzTrans trans, REQUEST from, String days) { - TimeTaken tt = trans.start("Extend User Credential", Env.SUB); - try { - Result 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> 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 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 value) { - // ensure credentials are sorted so we can fully automate Cred regression test - Collections.sort(value, new Comparator() { - @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 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 deleteUserCred(AuthzTrans trans, REQUEST from) { - final Result 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> rlcd = ques.credDAO.readID(trans, cred.value.id); - if(rlcd.notOKorIsEmpty()) { - // Empty Creds should have no user_roles. - Result> 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 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> nsr = ques.nsDAO.read(trans, cred.value.ns); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - switch(fd.status) { - case OK: - Result> 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: - Resultudr = 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> 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 doesCredentialMatch(AuthzTrans trans, REQUEST credReq) { - TimeTaken tt = trans.start("Does Credential Match", Env.SUB); - try { - // Note: Mapper assigns RAW type - Result 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 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 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 createUserRole(final AuthzTrans trans, REQUEST from) { - TimeTaken tt = trans.start("Create UserRole", Env.SUB); - try { - Result 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 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 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 nsr = ques.deriveNs(trans, userRole.role); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - switch(fd.status) { - case OK: - Result> 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 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 rrdd; - rrdd = RoleDAO.Data.decode(trans,ques,role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - // May Requester see result? - Result 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 userSet = new HashSet(); - Result> 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 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> 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 resetRolesForUser(AuthzTrans trans, REQUEST rreq) { - Result 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 currRoles = new HashSet(); - Result> rlurd = ques.userRoleDAO.readByUser(trans, rurdd.value.user); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { - currRoles.add(data.role); - } - } - - Result 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 rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - - rurdd.value.role(rrdd.value); - - Result nsd = ques.mayUser(trans, trans.user(), rrdd.value,Access.write); - if (nsd.notOK()) { - return Result.err(nsd); - } - Result 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 resetUsersForRole(AuthzTrans trans, REQUEST rreq) { - Result 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 nsd = ques.mayUser(trans, trans.user(), rd, Access.write); - if (nsd.notOK()) { - return Result.err(nsd); - } - - Result nsr = ques.deriveNs(trans, rurdd.value.role); - if(nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - Set currUsers = new HashSet(); - Result> 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 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 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 rrdd = RoleDAO.Data.decode(trans,ques,role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - - Result rcr = ques.mayUser(trans, trans.user(), rrdd.value, Access.write); - boolean mayNotChange; - if((mayNotChange = rcr.notOK()) && !trans.futureRequested()) { - return Result.err(rcr); - } - - Result> 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> 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 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 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 rns = ques.mayUser(trans, trans.user(), rdd, Access.write); - if(mayNotChange=rns.notOK()) { - if(!trans.futureRequested()) { - return Result.err(rns); - } - } - - Result> 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> 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 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 ns = ques.deriveNs(trans, role); -// if (ns.notOK()) return Result.err(ns); -// -// Result rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write); - // May calling user see by virtue of the Role - Result rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - Result rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - - HashSet userSet = new HashSet(); - Result> 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 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 ns = ques.deriveNs(trans, role); -// if (ns.notOK()) return Result.err(ns); -// -// Result rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write); - // May calling user see by virtue of the Role - Result rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - Result rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - - HashSet userSet = new HashSet(); - Result> 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 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 nss = ques.deriveNsSplit(trans, type); - if(nss.notOK()) { - return Result.err(nss); - } - - Result> 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 roleUsed = new HashSet(); - Set userSet = new HashSet(); - - if(!nss.isEmpty()) { - Result> 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> 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 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 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> resp = ques.historyDAO.readByUser(trans, user, yyyymm); - if(resp.notOK()) { - return Result.err(resp); - } - return mapper.history(trans, resp.value,sort); - } - - @Override - public Result 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 rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { - return Result.err(rrdd); - } - - Result rnd = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); - if(rnd.notOK()) { - return Result.err(rnd); - } - Result> 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 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 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> 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 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 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> 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 createDelegate(final AuthzTrans trans, REQUEST base) { - return createOrUpdateDelegate(trans, base, Question.Access.create); - } - - @Override - public Result updateDelegate(AuthzTrans trans, REQUEST base) { - return createOrUpdateDelegate(trans, base, Question.Access.write); - } - - - private Result createOrUpdateDelegate(final AuthzTrans trans, REQUEST base, final Access access) { - final Result 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> 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 rv = ques.mayUser(trans, dd, access); - if(rv.notOK()) { - return rv; - } - - Result 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> 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 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 deleteDelegate(AuthzTrans trans, REQUEST base) { - final Result 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> 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 rv = ques.mayUser(trans, dd, Access.write); - if(rv.notOK()) { - return rv; - } - - return ques.delegateDAO.delete(trans, dd, false); - } - - @Override - public Result 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> 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 rv = ques.mayUser(trans, dd, Access.write); - if(rv.notOK()) { - return rv; - } - - return ques.delegateDAO.delete(trans, dd, false); - } - - @Override - public Result 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 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> 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 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 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> 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 updateApproval(AuthzTrans trans, APPROVALS approvals) { - Result> 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> 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 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 changed(T src, T dflt) { - if(src!=null) { - return src; - } - return dflt; - } - - @Override - public Result 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> rapd = ques.approvalDAO.readByUser(trans, user); - if(rapd.isOK()) { - return mapper.approvals(rapd.value); - } else { - return Result.err(rapd); - } -} - - @Override - public Result 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> rapd = ques.approvalDAO.readByTicket(trans, uuid); - if(rapd.isOK()) { - return mapper.approvals(rapd.value); - } else { - return Result.err(rapd); - } - } - - @Override - public Result 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 listRapds = new ArrayList(); - - Result> myRapd = ques.approvalDAO.readByApprover(trans, approver); - if(myRapd.notOK()) { - return Result.err(myRapd); - } - - listRapds.addAll(myRapd.value); - - Result> 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> 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 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 cacheClear(AuthzTrans trans, String cname, int[] segment) { - if(ques.isGranted(trans,trans.user(),Define.ROOT_NS,CACHE,cname,"clear")) { - Result 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 { - public Mapper mapper(); - -/*********************************** - * NAMESPACE - ***********************************/ - /** - * - * @param trans - * @param user - * @param ns - * @return - * @throws DAOException - * @throws - */ - public Result createNS(AuthzTrans trans, REQUEST request, NsType type); - - /** - * - * @param trans - * @param ns - * @return - */ - public Result addAdminNS(AuthzTrans trans, String ns, String id); - - /** - * - * @param trans - * @param ns - * @return - */ - public Result delAdminNS(AuthzTrans trans, String ns, String id); - - /** - * - * @param trans - * @param ns - * @param id - * @return - */ - public Result addResponsibleNS(AuthzTrans trans, String ns, String id); - - /** - * - * @param trans - * @param ns - * @param id - * @return - */ - public Result delResponsibleNS(AuthzTrans trans, String ns, String id); - - /** - * - * @param trans - * @param ns - * @param key - * @param value - * @return - */ - public Result 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 deleteNsAttrib(AuthzTrans trans, String ns, String key); - - /** - * - * @param trans - * @param ns - * @param key - * @return - */ - public Result readNsByAttrib(AuthzTrans trans, String key); - - - /** - * - * @param trans - * @param ns - * @return - */ - public Result getNSbyName(AuthzTrans trans, String ns); - - /** - * - * @param trans - * @param user - * @return - */ - public Result getNSbyAdmin(AuthzTrans trans, String user, boolean full); - - /** - * - * @param trans - * @param user - * @return - */ - public Result getNSbyResponsible(AuthzTrans trans, String user, boolean full); - - /** - * - * @param trans - * @param user - * @return - */ - public Result getNSbyEither(AuthzTrans trans, String user, boolean full); - - /** - * - * @param trans - * @param parent - * @return - */ - public Result getNSsChildren(AuthzTrans trans, String parent); - - /** - * - * @param trans - * @param req - * @return - */ - public Result updateNsDescription(AuthzTrans trans, REQUEST req); - - /** - * - * @param trans - * @param ns - * @param user - * @return - * @throws DAOException - */ - public Result deleteNS(AuthzTrans trans, String ns); - -/*********************************** - * PERM - ***********************************/ - /** - * - * @param trans - * @param rreq - * @return - * @throws DAOException - * @throws MappingException - */ - public Result createPerm(AuthzTrans trans, REQUEST rreq); - - /** - * - * @param trans - * @param childPerm - * @return - * @throws DAOException - */ - public Result getPermsByType(AuthzTrans trans, String perm); - - /** - * - * @param trans - * @param type - * @param instance - * @param action - * @return - */ - public Result 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 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 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 getPermsByRole(AuthzTrans trans, String roleName); - - /** - * - * @param trans - * @param ns - * @return - */ - public Result getPermsByNS(AuthzTrans trans, String ns); - - /** - * rename permission - * - * @param trans - * @param rreq - * @param isRename - * @param origType - * @param origInstance - * @param origAction - * @return - */ - public Result renamePerm(AuthzTrans trans, REQUEST rreq, String origType, String origInstance, String origAction); - - /** - * - * @param trans - * @param req - * @return - */ - public Result updatePermDescription(AuthzTrans trans, REQUEST req); - - /** - * - * @param trans - * @param from - * @return - */ - public Result resetPermRoles(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param from - * @return - * @throws Exception - */ - public Result deletePerm(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param user - * @param perm - * @param type - * @param action - * @return - * @throws Exception - */ - Result 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 createRole(AuthzTrans trans, REQUEST req); - - /** - * - * @param trans - * @param role - * @return - */ - public Result getRolesByName(AuthzTrans trans, String role); - - /** - * - * @param trans - * @param user - * @return - * @throws DAOException - */ - public Result getRolesByUser(AuthzTrans trans, String user); - - /** - * - * @param trans - * @param user - * @return - */ - public Result getRolesByNS(AuthzTrans trans, String user); - - /** - * - * @param trans - * @param name - * @return - */ - public Result getRolesByNameOnly(AuthzTrans trans, String name); - - /** - * - * @param trans - * @param type - * @param instance - * @param action - * @return - */ - public Result getRolesByPerm(AuthzTrans trans, String type, String instance, String action); - - /** - * - * @param trans - * @param req - * @return - */ - public Result updateRoleDescription(AuthzTrans trans, REQUEST req); - - /** - * - * @param trans - * @param rreq - * @return - * @throws DAOException - */ - public Result addPermToRole(AuthzTrans trans, REQUEST rreq); - - - /** - * - * @param trans - * @param rreq - * @return - * @throws DAOException - */ - Result delPermFromRole(AuthzTrans trans, REQUEST rreq); - - - /** - * - * @param trans - * @param user - * @param role - * @return - * @throws DAOException - * @throws MappingException - */ - public Result deleteRole(AuthzTrans trans, String role); - - /** - * - * @param trans - * @param req - * @return - */ - public Result deleteRole(AuthzTrans trans, REQUEST req); - -/*********************************** - * CRED - ***********************************/ - - /** - * - * @param trans - * @param from - * @return - */ - Result createUserCred(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param from - * @return - */ - Result changeUserCred(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param from - * @param days - * @return - */ - Result extendUserCred(AuthzTrans trans, REQUEST from, String days); - - /** - * - * @param trans - * @param ns - * @return - */ - public Result getCredsByNS(AuthzTrans trans, String ns); - - /** - * - * @param trans - * @param id - * @return - */ - public Result getCredsByID(AuthzTrans trans, String id); - - /** - * - * @param trans - * @param req - * @param id - * @return - */ - public Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id); - - /** - * - * @param trans - * @param credReq - * @return - */ - public Result deleteUserCred(AuthzTrans trans, REQUEST credReq); - - /** - * - * @param trans - * @param user - * @return - * @throws Exception - */ - public Result doesCredentialMatch(AuthzTrans trans, REQUEST credReq); - - /** - * - * @param trans - * @param basicAuth - * @return - */ - public Result validateBasicAuth(AuthzTrans trans, String basicAuth); - - /** - * - * @param trans - * @param role - * @return - */ - public Result getUsersByRole(AuthzTrans trans, String role); - - /** - * - * @param trans - * @param role - * @return - */ - public Result getUserInRole(AuthzTrans trans, String user, String role); - - /** - * - * @param trans - * @param type - * @param instance - * @param action - * @return - */ - public Result getUsersByPermission(AuthzTrans trans,String type, String instance, String action); - - - - -/*********************************** - * USER-ROLE - ***********************************/ - /** - * - * @param trans - * @param user - * @param request - * @return - * @throws Exception - */ - public Result createUserRole(AuthzTrans trans, REQUEST request); - - /** - * - * @param trans - * @param role - * @return - */ - public Result getUserRolesByRole(AuthzTrans trans, String role); - - /** - * - * @param trans - * @param role - * @return - */ - public Result getUserRolesByUser(AuthzTrans trans, String user); - - /** - * - * @param trans - * @param from - * @return - */ - public Result resetRolesForUser(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param from - * @return - */ - public Result resetUsersForRole(AuthzTrans trans, REQUEST from); - - /** - * - * @param trans - * @param user - * @param role - * @return - */ - public Result extendUserRole(AuthzTrans trans, String user, - String role); - - /** - * - * @param trans - * @param user - * @param usr - * @param role - * @return - * @throws DAOException - */ - public Result deleteUserRole(AuthzTrans trans, String usr, String role); - - - -/*********************************** - * HISTORY - ***********************************/ - /** - * - * @param trans - * @param user - * @param yyyymm - * @return - */ - public Result getHistoryByUser(AuthzTrans trans, String user, int[] yyyymm, int sort); - - /** - * - * @param trans - * @param subj - * @param yyyymm - * @param sort - * @return - */ - public Result getHistoryByRole(AuthzTrans trans, String subj, int[] yyyymm, int sort); - - /** - * - * @param trans - * @param subj - * @param yyyymm - * @param sort - * @return - */ - public Result getHistoryByPerm(AuthzTrans trans, String subj, int[] yyyymm, int sort); - - /** - * - * @param trans - * @param subj - * @param yyyymm - * @param sort - * @return - */ - public Result getHistoryByNS(AuthzTrans trans, String subj, int[] yyyymm, int sort); - -/*********************************** - * DELEGATE - ***********************************/ - /** - * - * @param trans - * @param delegates - * @return - * @throws Exception - */ - public Result createDelegate(AuthzTrans trans, REQUEST reqDelegate); - - /** - * - * @param trans - * @param delegates - * @return - * @throws Exception - */ - public Result updateDelegate(AuthzTrans trans, REQUEST reqDelegate); - - /** - * - * @param trans - * @param userName - * @param delegate - * @return - * @throws Exception - */ - public Result deleteDelegate(AuthzTrans trans, REQUEST reqDelegate); - - /** - * - * @param trans - * @param userName - * @return - */ - public Result deleteDelegate(AuthzTrans trans, String userName); - - /** - * - * @param trans - * @param user - * @return - * @throws Exception - */ - public Result getDelegatesByUser(AuthzTrans trans, String user); - - - /** - * - * @param trans - * @param delegate - * @return - */ - public Result getDelegatesByDelegate(AuthzTrans trans, String delegate); - -/*********************************** - * APPROVAL - ***********************************/ - /** - * - * @param trans - * @param user - * @param approver - * @param status - * @return - */ - public Result updateApproval(AuthzTrans trans, APPROVALS approvals); - - /** - * - * @param trans - * @param user - * @return - */ - public Result getApprovalsByUser(AuthzTrans trans, String user); - - /** - * - * @param trans - * @param ticket - * @return - */ - public Result getApprovalsByTicket(AuthzTrans trans, String ticket); - - /** - * - * @param trans - * @param approver - * @return - */ - public Result getApprovalsByApprover(AuthzTrans trans, String approver); - - /** - * - * @param trans - * @param cname - * @return - */ - public Result cacheClear(AuthzTrans trans, String cname); - - /** - * - * @param trans - * @param cname - * @param segment - * @return - */ - public Result 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 implements Cloneable { - public boolean useJSON; - - public Code(AuthzFacade facade, String description, boolean useJSON, String ... roles) { - super(facade, description, roles); - this.useJSON = useJSON; - } - - public 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 ai= new ArrayList(); - 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 Marshal getMarshal(API api); - public A newInstance(API api); - - public Result permkey(AuthzTrans trans, PERMKEY from); - public Result perm(AuthzTrans trans, REQUEST from); - public Result role(AuthzTrans trans, REQUEST from); - public Result ns(AuthzTrans trans, REQUEST from); - public Result cred(AuthzTrans trans, REQUEST from, boolean requiresPass); - public Result cred(List lcred, USERS to); - public Result cert(List lcert, CERTS to); - public Result delegate(AuthzTrans trans, REQUEST from); - public Result delegate(List lDelg); - public Result approvals(List lAppr); - public Result> approvals(APPROVALS apprs); - public Result> perms(AuthzTrans trans, PERMS perms); - - public Result userRole(AuthzTrans trans, REQUEST from); - public Result permFromRPRequest(AuthzTrans trans, REQUEST from); - public Result roleFromRPRequest(AuthzTrans trans, REQUEST from); - - /* - * Check Requests of varying sorts for Future fields set - */ - public Result future(AuthzTrans trans, String table, REQUEST from, Bytification content, boolean enableApproval, Memo memo, MayChange mc); - - public Result nss(AuthzTrans trans, Namespace from, NSS to); - - // Note: Prevalidate if NS given is allowed to be seen before calling - public Result nss(AuthzTrans trans, Collection from, NSS to); -// public Result ns_attrib(AuthzTrans trans, Set from, NSS to); - public Result perms(AuthzTrans trans, List from, PERMS to, boolean filter); - public Result roles(AuthzTrans trans, List from, ROLES roles, boolean filter); - // Note: Prevalidate if NS given is allowed to be seen before calling - public Result users(AuthzTrans trans, Collection from, USERS to); - public Result userRoles(AuthzTrans trans, Collection from, USERROLES to); - public Result keys(Collection from); - - public Result history(AuthzTrans trans, List 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 { - 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 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(AuthzTrans trans, Namespace from, Nss to) { - List 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 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(AuthzTrans trans, Collection from, Nss to) { - List 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 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(AuthzTrans trans, List from, Perms to, boolean filter) { - List 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() { - @Override - public int compare(Perm perm1, Perm perm2) { - int typeCompare = perm1.getType().compareToIgnoreCase(perm2.getType()); - if (typeCompare == 0) { - int instanceCompare = perm1.getInstance().compareToIgnoreCase(perm2.getInstance()); - if (instanceCompare == 0) { - return perm1.getAction().compareToIgnoreCase(perm2.getAction()); - } - return instanceCompare; - } - return typeCompare; - } - }); - } finally { - tt.done(); - } - return Result.ok(to); - } - - @Override - public Result> perms(AuthzTrans trans, Perms perms) { - List lpd = new ArrayList(); - for (Perm p : perms.getPerm()) { - Result 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 permkey(AuthzTrans trans, Pkey from) { - return q.permFrom(trans, from.getType(),from.getInstance(),from.getAction()); - } - - @Override - public Result 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 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 roleFromRPRequest(AuthzTrans trans, Request req) { - RolePermRequest from = (RolePermRequest)req; - Result 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 perm(AuthzTrans trans, Request req) { - PermRequest from = (PermRequest)req; - Result 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 role(AuthzTrans trans, Request base) { - RoleRequest from = (RoleRequest)base; - Result 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(AuthzTrans trans, List 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 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(AuthzTrans trans, Collection from, Users to) { - List 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(AuthzTrans trans, Collection from, UserRoles to) { - List 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 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 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 cred(List from, Users to) { - List 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 cert(List from, Certs to) { - List 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 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 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(AuthzTrans trans, List history, final int sort) { - History hist = new History(); - List 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() { - @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 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 Marshal getMarshal(API api) { - switch(api) { - case CERTS: return (Marshal) new CertsMarshal(); - default: - return null; - } - } - - @Override - public Result approvals(List lAppr) { - Approvals apprs = new Approvals(); - List 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> approvals(Approvals apprs) { - List lappr = new ArrayList(); - 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 delegate(List lDelg) { - Delgs delgs = new Delgs(); - List 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 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(Collection 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 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 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 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 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 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; - } - - -} -- cgit 1.2.3-korg