diff options
author | sg481n <sg481n@att.com> | 2017-08-28 12:11:35 -0400 |
---|---|---|
committer | sg481n <sg481n@att.com> | 2017-08-28 12:11:47 -0400 |
commit | bd890c575163e4d87ac24198b9c68a39cf4bbc4d (patch) | |
tree | 2d6c5baa66d1df8f8c841d39646e93020ed203bc /authz-service/src/main/java/org | |
parent | 72b21f2ac109b0d95fef3ef608c0c343337d4ce2 (diff) |
Update project structure to org.onap.aaf
Update project structure of authz module in aaf from
com.att to org.onap.aaf and add distribution management
and repositories.
Issue-id: AAF-21
Change-Id: Ia2486954e99f2bd60f18122ed60d32d5590781e9
Signed-off-by: sg481n <sg481n@att.com>
Diffstat (limited to 'authz-service/src/main/java/org')
26 files changed, 12168 insertions, 0 deletions
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/cadi/DirectAAFLur.java b/authz-service/src/main/java/org/onap/aaf/authz/cadi/DirectAAFLur.java new file mode 100644 index 00000000..67dc7540 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/cadi/DirectAAFLur.java @@ -0,0 +1,170 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.cadi;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+
+import java.security.Principal;
+import java.util.List;
+
+import org.onap.aaf.authz.env.AuthzEnv;
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.dao.aaf.cass.PermDAO;
+import org.onap.aaf.dao.aaf.cass.PermDAO.Data;
+import org.onap.aaf.dao.aaf.hl.Question;
+
+import org.onap.aaf.cadi.Lur;
+import org.onap.aaf.cadi.Permission;
+
+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<List<Data>> 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<Permission> permissions) {
+ Result<List<Data>> 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/org/onap/aaf/authz/cadi/DirectAAFUserPass.java b/authz-service/src/main/java/org/onap/aaf/authz/cadi/DirectAAFUserPass.java new file mode 100644 index 00000000..263c94e8 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/cadi/DirectAAFUserPass.java @@ -0,0 +1,74 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.cadi;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+
+import java.util.Date;
+
+import org.onap.aaf.authz.env.AuthzEnv;
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.dao.DAOException;
+import org.onap.aaf.dao.aaf.hl.Question;
+
+import org.onap.aaf.cadi.CredVal;
+
+/**
+ * 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<Date> 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/org/onap/aaf/authz/cadi/DirectCertIdentity.java b/authz-service/src/main/java/org/onap/aaf/authz/cadi/DirectCertIdentity.java new file mode 100644 index 00000000..7df3adc3 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/cadi/DirectCertIdentity.java @@ -0,0 +1,79 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.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 org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.cssa.rserv.TransFilter;
+import org.onap.aaf.dao.aaf.cached.CachedCertDAO;
+import org.onap.aaf.dao.aaf.cass.CertDAO.Data;
+
+import org.onap.aaf.cadi.principal.X509Principal;
+import org.onap.aaf.cadi.taf.cert.CertIdentity;
+import org.onap.aaf.cadi.taf.cert.X509Taf;
+
+/**
+ * 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<List<Data>> 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/org/onap/aaf/authz/facade/AuthzFacade.java b/authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacade.java new file mode 100644 index 00000000..69df9c6d --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacade.java @@ -0,0 +1,263 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.facade;
+
+import java.util.Date;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.cssa.rserv.RServlet;
+import org.onap.aaf.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<Void> requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type);
+
+ public abstract Result<Void> getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns);
+
+ public abstract Result<Void> getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full);
+
+ public abstract Result<Void> getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full);
+
+ public abstract Result<Void> getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full);
+
+ public abstract Result<Void> getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String pathParam);
+
+ public abstract Result<Void> addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id);
+
+ public abstract Result<Void> delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id);
+
+ public abstract Result<Void> addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id);
+
+ public abstract Result<Void> delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id);
+
+ public abstract Result<Void> updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns);
+
+ // NS Attribs
+ public abstract Result<Void> createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value);
+
+ public abstract Result<Void> readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key);
+
+ public abstract Result<Void> updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value);
+
+ public abstract Result<Void> delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key);
+
+ /*
+ * Permissions
+ */
+ public abstract Result<Void> createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> getPermsByName(AuthzTrans trans, HttpServletResponse resp,
+ String type, String instance, String action);
+
+ public abstract Result<Void> getPermsByUser(AuthzTrans trans, HttpServletResponse response, String user);
+
+ public abstract Result<Void> getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest request, HttpServletResponse response, String user);
+
+ public abstract Result<Void> getPermsByType(AuthzTrans trans, HttpServletResponse resp, String type);
+
+ public abstract Result<Void> getPermsForRole(AuthzTrans trans, HttpServletResponse response, String roleName);
+
+ public abstract Result<Void> getPermsByNS(AuthzTrans trans, HttpServletResponse response, String ns);
+
+ public abstract Result<Void> renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp,
+ String type, String instance, String action);
+
+ public abstract Result<Void> updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> deletePerm(AuthzTrans trans, HttpServletResponse resp,
+ String perm, String type, String action);
+
+ /*
+ * Roles
+ */
+ public abstract Result<Void> createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse response);
+
+ public abstract Result<Void> getRolesByName(AuthzTrans trans,HttpServletResponse resp, String name);
+
+ public abstract Result<Void> getRolesByNS(AuthzTrans trans, HttpServletResponse resp, String ns);
+
+ public abstract Result<Void> getRolesByNameOnly(AuthzTrans trans, HttpServletResponse resp, String nameOnly);
+
+ public abstract Result<Void> getRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user);
+
+ public abstract Result<Void> getRolesByPerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action);
+
+ public abstract Result<Void> updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> addPermToRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> delPermFromRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> deleteRole(AuthzTrans trans, HttpServletResponse resp, String role);
+
+ /*
+ * Users
+ */
+
+ public abstract Result<Void> getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role);
+
+ public abstract Result<Void> getUsersByPermission(AuthzTrans trans, HttpServletResponse resp,
+ String type, String instance, String action);
+
+
+
+ /*
+ * Delegates
+ */
+ public abstract Result<Void> createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> deleteDelegate(AuthzTrans trans, String user);
+
+ public abstract Result<Void> getDelegatesByUser(AuthzTrans trans, String userName, HttpServletResponse resp);
+
+ public abstract Result<Void> getDelegatesByDelegate(AuthzTrans trans, String userName, HttpServletResponse resp);
+
+ /*
+ * Credentials
+ */
+ public abstract Result<Void> createUserCred(AuthzTrans trans, HttpServletRequest req);
+
+ public abstract Result<Void> changeUserCred(AuthzTrans trans, HttpServletRequest req);
+
+ public abstract Result<Void> extendUserCred(AuthzTrans trans, HttpServletRequest req, String days);
+
+ public abstract Result<Void> getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns);
+
+ public abstract Result<Void> getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id);
+
+ public abstract Result<Void> deleteUserCred(AuthzTrans trans, HttpServletRequest req);
+
+ public abstract Result<Void> validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth);
+
+ public abstract Result<Date> doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ /*
+ * Miscellaneous
+ */
+ /**
+ * Place Standard Messages based on HTTP Code onto Error Data Structure, and write to OutputStream
+ * Log message
+ */
+ public abstract void error(AuthzTrans trans, HttpServletResponse response, Result<?> result);
+
+ /*
+ * UserRole
+ */
+ public abstract Result<Void> requestUserRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role);
+
+ public abstract Result<Void> getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role);
+
+ public abstract Result<Void> getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user);
+
+ public abstract Result<Void> deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role);
+
+ public abstract Result<Void> resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req);
+
+ public abstract Result<Void> resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req);
+
+ public abstract Result<Void> extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user,
+ String role);
+
+ /*
+ * Approval
+ */
+ public abstract Result<Void> updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp);
+
+ public abstract Result<Void> getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user);
+
+ public abstract Result<Void> getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket);
+
+ public abstract Result<Void> getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver);
+
+
+ /*
+ * History
+ */
+ public abstract Result<Void> getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort);
+
+ public abstract Result<Void> getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort);
+
+ public abstract Result<Void> getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort);
+
+ public abstract Result<Void> getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort);
+
+ /*
+ * Cache
+ */
+ public abstract Result<Void> cacheClear(AuthzTrans trans, String pathParam);
+
+ public abstract Result<Void> cacheClear(AuthzTrans trans, String string,String segments);
+
+ public abstract void dbReset(AuthzTrans trans);
+
+
+
+ /*
+ * API
+ */
+ public Result<Void> getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet<AuthzTrans> rservlet);
+
+ public abstract Result<Void> getAPIExample(AuthzTrans trans, HttpServletResponse resp, String typeCode, boolean optional);
+
+ public abstract Result<Void> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id);
+
+
+
+
+
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacadeFactory.java b/authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacadeFactory.java new file mode 100644 index 00000000..8097317c --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacadeFactory.java @@ -0,0 +1,57 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.facade;
+
+import org.onap.aaf.authz.env.AuthzEnv;
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.service.AuthzCassServiceImpl;
+import org.onap.aaf.authz.service.mapper.Mapper_2_0;
+import org.onap.aaf.dao.aaf.hl.Question;
+
+import org.onap.aaf.inno.env.APIException;
+import org.onap.aaf.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/org/onap/aaf/authz/facade/AuthzFacadeImpl.java b/authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacadeImpl.java new file mode 100644 index 00000000..d35a95a1 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacadeImpl.java @@ -0,0 +1,2565 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.facade;
+
+import static org.onap.aaf.authz.layer.Result.ERR_ActionNotCompleted;
+import static org.onap.aaf.authz.layer.Result.ERR_Backend;
+import static org.onap.aaf.authz.layer.Result.ERR_BadData;
+import static org.onap.aaf.authz.layer.Result.ERR_ConflictAlreadyExists;
+import static org.onap.aaf.authz.layer.Result.ERR_Denied;
+import static org.onap.aaf.authz.layer.Result.ERR_NotFound;
+import static org.onap.aaf.authz.layer.Result.ERR_NotImplemented;
+import static org.onap.aaf.authz.layer.Result.ERR_Policy;
+import static org.onap.aaf.authz.layer.Result.ERR_Security;
+import static org.onap.aaf.authz.layer.Result.OK;
+import static org.onap.aaf.dao.aaf.cass.Status.ERR_ChoiceNeeded;
+import static org.onap.aaf.dao.aaf.cass.Status.ERR_DelegateNotFound;
+import static org.onap.aaf.dao.aaf.cass.Status.ERR_DependencyExists;
+import static org.onap.aaf.dao.aaf.cass.Status.ERR_FutureNotRequested;
+import static org.onap.aaf.dao.aaf.cass.Status.ERR_InvalidDelegate;
+import static org.onap.aaf.dao.aaf.cass.Status.ERR_NsNotFound;
+import static org.onap.aaf.dao.aaf.cass.Status.ERR_PermissionNotFound;
+import static org.onap.aaf.dao.aaf.cass.Status.ERR_RoleNotFound;
+import static org.onap.aaf.dao.aaf.cass.Status.ERR_UserNotFound;
+import static org.onap.aaf.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 org.onap.aaf.authz.env.AuthzEnv;
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.layer.FacadeImpl;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthzCassServiceImpl;
+import org.onap.aaf.authz.service.AuthzService;
+import org.onap.aaf.authz.service.mapper.Mapper;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+import org.onap.aaf.cssa.rserv.RServlet;
+import org.onap.aaf.cssa.rserv.RouteReport;
+import org.onap.aaf.cssa.rserv.doc.ApiDoc;
+import org.onap.aaf.dao.aaf.cass.NsType;
+import org.onap.aaf.dao.aaf.cass.Status;
+import org.onap.aaf.dao.aaf.hl.Question;
+
+import org.onap.aaf.cadi.aaf.client.Examples;
+import org.onap.aaf.inno.env.APIException;
+import org.onap.aaf.inno.env.Data;
+import org.onap.aaf.inno.env.Data.TYPE;
+import org.onap.aaf.inno.env.Env;
+import org.onap.aaf.inno.env.TimeTaken;
+import org.onap.aaf.inno.env.util.Chrono;
+import org.onap.aaf.rosetta.Marshal;
+import org.onap.aaf.rosetta.env.RosettaDF;
+import org.onap.aaf.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<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> extends FacadeImpl implements AuthzFacade
+ {
+ private static final String FORBIDDEN = "Forbidden";
+ private static final String NOT_FOUND = "Not Found";
+ private static final String NOT_ACCEPTABLE = "Not Acceptable";
+ private static final String GENERAL_SERVICE_ERROR = "General Service Error";
+ private static final String NO_DATA = "***No Data***";
+ private AuthzService<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> service = null;
+ private final RosettaDF<NSS> nssDF;
+ private final RosettaDF<PERMS> permsDF;
+ private final RosettaDF<ROLES> roleDF;
+ private final RosettaDF<USERS> usersDF;
+ private final RosettaDF<USERROLES> userrolesDF;
+ private final RosettaDF<CERTS> certsDF;
+ private final RosettaDF<DELGS> delgDF;
+ private final RosettaDF<REQUEST> permRequestDF;
+ private final RosettaDF<REQUEST> roleRequestDF;
+ private final RosettaDF<REQUEST> userRoleRequestDF;
+ private final RosettaDF<REQUEST> rolePermRequestDF;
+ private final RosettaDF<REQUEST> nsRequestDF;
+ private final RosettaDF<REQUEST> credRequestDF;
+ private final RosettaDF<REQUEST> delgRequestDF;
+ private final RosettaDF<HISTORY> historyDF;
+ private final RosettaDF<KEYS> keysDF;
+
+ private final RosettaDF<ERR> errDF;
+ private final RosettaDF<APPROVALS> approvalDF;
+ // Note: Api is not different per Version
+ private final RosettaDF<Api> apiDF;
+
+
+ @SuppressWarnings("unchecked")
+ public AuthzFacadeImpl(AuthzEnv env, AuthzService<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> service, Data.TYPE dataType) throws APIException {
+ this.service = service;
+ (nssDF = env.newDataFactory(service.mapper().getClass(API.NSS))).in(dataType).out(dataType);
+ (permRequestDF = env.newDataFactory(service.mapper().getClass(API.PERM_REQ))).in(dataType).out(dataType);
+ (permsDF = env.newDataFactory(service.mapper().getClass(API.PERMS))).in(dataType).out(dataType);
+// (permKeyDF = env.newDataFactory(service.mapper().getClass(API.PERM_KEY))).in(dataType).out(dataType);
+ (roleDF = env.newDataFactory(service.mapper().getClass(API.ROLES))).in(dataType).out(dataType);
+ (roleRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_REQ))).in(dataType).out(dataType);
+ (usersDF = env.newDataFactory(service.mapper().getClass(API.USERS))).in(dataType).out(dataType);
+ (userrolesDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLES))).in(dataType).out(dataType);
+ (certsDF = env.newDataFactory(service.mapper().getClass(API.CERTS))).in(dataType).out(dataType)
+ .rootMarshal((Marshal<CERTS>) service.mapper().getMarshal(API.CERTS));
+ ;
+ (userRoleRequestDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLE_REQ))).in(dataType).out(dataType);
+ (rolePermRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_PERM_REQ))).in(dataType).out(dataType);
+ (nsRequestDF = env.newDataFactory(service.mapper().getClass(API.NS_REQ))).in(dataType).out(dataType);
+ (credRequestDF = env.newDataFactory(service.mapper().getClass(API.CRED_REQ))).in(dataType).out(dataType);
+ (delgRequestDF = env.newDataFactory(service.mapper().getClass(API.DELG_REQ))).in(dataType).out(dataType);
+ (historyDF = env.newDataFactory(service.mapper().getClass(API.HISTORY))).in(dataType).out(dataType);
+ ( keysDF = env.newDataFactory(service.mapper().getClass(API.KEYS))).in(dataType).out(dataType);
+ (delgDF = env.newDataFactory(service.mapper().getClass(API.DELGS))).in(dataType).out(dataType);
+ (approvalDF = env.newDataFactory(service.mapper().getClass(API.APPROVALS))).in(dataType).out(dataType);
+ (errDF = env.newDataFactory(service.mapper().getClass(API.ERROR))).in(dataType).out(dataType);
+ (apiDF = env.newDataFactory(Api.class)).in(dataType).out(dataType);
+ }
+
+ public Mapper<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper() {
+ return service.mapper();
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#error(org.onap.aaf.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 org.onap.aaf.authz.facade.AuthzFacade#createNS(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ @Override
+ public Result<Void> requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type) {
+ TimeTaken tt = trans.start(CREATE_NS, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST request;
+ try {
+ Data<REQUEST> rd = nsRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,rd.asString());
+ }
+ request = rd.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,CREATE_NS);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+ }
+
+ Result<Void> rp = service.createNS(trans,request,type);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,nsRequestDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,CREATE_NS);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#addAdminToNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) {
+ TimeTaken tt = trans.start(ADD_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS);
+ try {
+ Result<Void> rp = service.addAdminNS(trans,ns,id);
+ switch(rp.status) {
+ case OK:
+ //TODO Perms??
+ setContentType(resp,nsRequestDF.getOutType());
+ resp.getOutputStream().println();
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,ADD_NS_ADMIN);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#delAdminFromNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) {
+ TimeTaken tt = trans.start(DELETE_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS);
+ try {
+ Result<Void> rp = service.delAdminNS(trans, ns, id);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,nsRequestDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_NS_ADMIN);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#addAdminToNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) {
+ TimeTaken tt = trans.start(ADD_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS);
+ try {
+ Result<Void> rp = service.addResponsibleNS(trans,ns,id);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,nsRequestDF.getOutType());
+ resp.getOutputStream().println();
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,ADD_NS_RESPONSIBLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#delAdminFromNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) {
+ TimeTaken tt = trans.start(DELETE_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS);
+ try {
+ Result<Void> rp = service.delResponsibleNS(trans, ns, id);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,nsRequestDF.getOutType());
+ resp.getOutputStream().println();
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_NS_RESPONSIBLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getNSsByName(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns) {
+ TimeTaken tt = trans.start(GET_NS_BY_NAME + ' ' + ns, Env.SUB|Env.ALWAYS);
+ try {
+ Result<NSS> rp = service.getNSbyName(trans, ns);
+ switch(rp.status) {
+ case OK:
+ RosettaData<NSS> data = nssDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,nssDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_NS_BY_NAME);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getNSsByAdmin(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){
+ TimeTaken tt = trans.start(GET_NS_BY_ADMIN + ' ' + user, Env.SUB|Env.ALWAYS);
+ try {
+ Result<NSS> rp = service.getNSbyAdmin(trans, user, full);
+ switch(rp.status) {
+ case OK:
+ RosettaData<NSS> data = nssDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,nssDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_NS_BY_ADMIN);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){
+ TimeTaken tt = trans.start(GET_NS_BY_RESPONSIBLE + ' ' + user, Env.SUB|Env.ALWAYS);
+ try {
+ Result<NSS> rp = service.getNSbyResponsible(trans, user, full);
+ switch(rp.status) {
+ case OK:
+ RosettaData<NSS> data = nssDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+
+ setContentType(resp,nssDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_NS_BY_RESPONSIBLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){
+ TimeTaken tt = trans.start(GET_NS_BY_EITHER + ' ' + user, Env.SUB|Env.ALWAYS);
+ try {
+ Result<NSS> rp = service.getNSbyEither(trans, user, full);
+
+ switch(rp.status) {
+ case OK:
+ RosettaData<NSS> data = nssDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+
+ setContentType(resp,nssDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_NS_BY_EITHER);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String parent){
+ TimeTaken tt = trans.start(GET_NS_CHILDREN + ' ' + parent, Env.SUB|Env.ALWAYS);
+ try {
+ Result<NSS> rp = service.getNSsChildren(trans, parent);
+ switch(rp.status) {
+ case OK:
+ RosettaData<NSS> data = nssDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,nssDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_NS_CHILDREN);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(UPDATE_NS_DESC, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = nsRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,UPDATE_NS_DESC);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+
+ }
+ Result<Void> rp = service.updateNsDescription(trans, rreq);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,nsRequestDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,UPDATE_NS_DESC);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#requestNS(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ @Override
+ public Result<Void> deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns) {
+ TimeTaken tt = trans.start(DELETE_NS + ' ' + ns, Env.SUB|Env.ALWAYS);
+ try {
+ Result<Void> rp = service.deleteNS(trans,ns);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,nsRequestDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_NS);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ private final static String NS_CREATE_ATTRIB = "nsCreateAttrib";
+ private final static String NS_UPDATE_ATTRIB = "nsUpdateAttrib";
+ private final static String READ_NS_BY_ATTRIB = "readNsByAttrib";
+ private final static String NS_DELETE_ATTRIB = "nsDeleteAttrib";
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#createAttribForNS(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) {
+ TimeTaken tt = trans.start(NS_CREATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS);
+ try {
+ Result<?> rp = service.createNsAttrib(trans,ns,key,value);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp, keysDF.getOutType());
+ resp.getOutputStream().println();
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,NS_CREATE_ATTRIB);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#readAttribForNS(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key) {
+ TimeTaken tt = trans.start(READ_NS_BY_ATTRIB + ' ' + key, Env.SUB|Env.ALWAYS);
+ try {
+ Result<KEYS> rp = service.readNsByAttrib(trans, key);
+ switch(rp.status) {
+ case OK:
+ RosettaData<KEYS> data = keysDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,keysDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,READ_NS_BY_ATTRIB);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#updAttribForNS(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value) {
+ TimeTaken tt = trans.start(NS_UPDATE_ATTRIB + ' ' + ns + ':'+key+':'+value, Env.SUB|Env.ALWAYS);
+ try {
+ Result<?> rp = service.updateNsAttrib(trans,ns,key,value);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp, keysDF.getOutType());
+ resp.getOutputStream().println();
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,NS_UPDATE_ATTRIB);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#delAttribForNS(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key) {
+ TimeTaken tt = trans.start(NS_DELETE_ATTRIB + ' ' + ns + ':'+key, Env.SUB|Env.ALWAYS);
+ try {
+ Result<?> rp = service.deleteNsAttrib(trans,ns,key);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp, keysDF.getOutType());
+ resp.getOutputStream().println();
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,NS_DELETE_ATTRIB);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+//
+// PERMISSION
+//
+ public static final String CREATE_PERMISSION = "createPermission";
+ public static final String GET_PERMS_BY_TYPE = "getPermsByType";
+ public static final String GET_PERMS_BY_NAME = "getPermsByName";
+ public static final String GET_PERMISSIONS_BY_USER = "getPermissionsByUser";
+ public static final String GET_PERMISSIONS_BY_USER_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 org.onap.aaf.authz.facade.AuthzFacade#createOrUpdatePerm(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, java.lang.String, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start( CREATE_PERMISSION, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,CREATE_PERMISSION);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+ }
+
+ Result<Void> rp = service.createPerm(trans,rreq);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,CREATE_PERMISSION);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getChildPerms(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getPermsByType(AuthzTrans trans, HttpServletResponse resp, String perm) {
+ TimeTaken tt = trans.start(GET_PERMS_BY_TYPE + ' ' + perm, Env.SUB|Env.ALWAYS);
+ try {
+
+ Result<PERMS> rp = service.getPermsByType(trans, perm);
+ switch(rp.status) {
+ case OK:
+ RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_PERMS_BY_TYPE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> getPermsByName(AuthzTrans trans, HttpServletResponse resp,
+ String type, String instance, String action) {
+
+ TimeTaken tt = trans.start(GET_PERMS_BY_NAME + ' ' + type
+ + '|' + instance + '|' + action, Env.SUB|Env.ALWAYS);
+ try {
+
+ Result<PERMS> rp = service.getPermsByName(trans, type, instance, action);
+ switch(rp.status) {
+ case OK:
+ RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,permsDF.getOutType());
+ 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 org.onap.aaf.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getPermsByUser(AuthzTrans trans, HttpServletResponse resp, String user) {
+ TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS);
+ try {
+ Result<PERMS> rp = service.getPermsByUser(trans, user);
+ switch(rp.status) {
+ case OK:
+ RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,permsDF.getOutType());
+ 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 org.onap.aaf.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String user) {
+ TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER_WITH_QUERY + ' ' + user, Env.SUB|Env.ALWAYS);
+ try {
+ PERMS perms;
+ try {
+ RosettaData<PERMS> data = permsDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ perms = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,CREATE_PERMISSION);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+ }
+
+ Result<PERMS> rp = service.getPermsByUser(trans, perms, user);
+ switch(rp.status) {
+ case OK:
+ RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,permsDF.getOutType());
+ 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 org.onap.aaf.authz.facade.AuthzFacade#getPermissionsForRole(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getPermsForRole(AuthzTrans trans, HttpServletResponse resp, String roleName) {
+ TimeTaken tt = trans.start(GET_PERMISSIONS_BY_ROLE + ' ' + roleName, Env.SUB|Env.ALWAYS);
+ try {
+ Result<PERMS> rp = service.getPermsByRole(trans, roleName);
+ switch(rp.status) {
+ case OK:
+ RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_PERMISSIONS_BY_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> getPermsByNS(AuthzTrans trans,HttpServletResponse resp,String ns) {
+ TimeTaken tt = trans.start(GET_PERMISSIONS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS);
+ try {
+ Result<PERMS> rp = service.getPermsByNS(trans, ns);
+ switch(rp.status) {
+ case OK:
+ RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,permsDF.getOutType());
+ 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 org.onap.aaf.authz.facade.AuthzFacade#createOrUpdatePerm(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean, java.lang.String, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp,
+ String origType, String origInstance, String origAction) {
+ String cmdDescription = UPDATE_PERMISSION;
+ TimeTaken tt = trans.start( cmdDescription + ' ' + origType + ' ' + origInstance + ' ' + origAction, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,cmdDescription);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+ }
+
+ Result<Void> rp = service.renamePerm(trans,rreq, origType, origInstance, origAction);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,cmdDescription);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(UPDATE_PERM_DESC, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,UPDATE_PERM_DESC);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+
+ }
+ Result<Void> rp = service.updatePermDescription(trans, rreq);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permRequestDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,UPDATE_PERM_DESC);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+
+ @Override
+ public Result<Void> resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(SET_PERMISSION_ROLES_TO, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = rolePermRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN, SET_PERMISSION_ROLES_TO);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+ }
+
+ Result<Void> rp = service.resetPermRoles(trans, rreq);
+
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,SET_PERMISSION_ROLES_TO);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(DELETE_PERMISSION, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,DELETE_PERMISSION);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+
+ }
+
+ Result<Void> rp = service.deletePerm(trans,rreq);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_PERMISSION);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> deletePerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action) {
+ TimeTaken tt = trans.start(DELETE_PERMISSION + type + ' ' + instance + ' ' + action, Env.SUB|Env.ALWAYS);
+ try {
+ Result<Void> rp = service.deletePerm(trans,type,instance,action);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_PERMISSION);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ public static final String CREATE_ROLE = "createRole";
+ public static final String GET_ROLES_BY_USER = "getRolesByUser";
+ public static final String GET_ROLES_BY_NS = "getRolesByNS";
+ public static final String GET_ROLES_BY_NAME_ONLY = "getRolesByNameOnly";
+ public static final String GET_ROLES_BY_NAME = "getRolesByName";
+ public static final String GET_ROLES_BY_PERM = "getRolesByPerm";
+ public static final String UPDATE_ROLE_DESC = "updateRoleDescription";
+ public static final String ADD_PERM_TO_ROLE = "addPermissionToRole";
+ public static final String DELETE_PERM_FROM_ROLE = "deletePermissionFromRole";
+ public static final String UPDATE_MGTPERM_ROLE = "updateMgtPermRole";
+ public static final String DELETE_ROLE = "deleteRole";
+ public static final String GET_CERT_BY_ID = "getCertByID";
+
+ @Override
+ public Result<Void> createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(CREATE_ROLE, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = roleRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,CREATE_ROLE);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+
+ }
+ Result<Void> rp = service.createRole(trans, rreq);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,roleRequestDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,CREATE_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getRolesByName(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getRolesByName(AuthzTrans trans, HttpServletResponse resp, String role) {
+ TimeTaken tt = trans.start(GET_ROLES_BY_NAME + ' ' + role, Env.SUB|Env.ALWAYS);
+ try {
+ Result<ROLES> rp = service.getRolesByName(trans, role);
+ switch(rp.status) {
+ case OK:
+ RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,roleDF.getOutType());
+ 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 org.onap.aaf.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getRolesByUser(AuthzTrans trans,HttpServletResponse resp, String user) {
+ TimeTaken tt = trans.start(GET_ROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS);
+ try {
+ Result<ROLES> rp = service.getRolesByUser(trans, user);
+ switch(rp.status) {
+ case OK:
+ RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,roleDF.getOutType());
+ 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 org.onap.aaf.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getRolesByNS(AuthzTrans trans,HttpServletResponse resp, String ns) {
+ TimeTaken tt = trans.start(GET_ROLES_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS);
+ try {
+ Result<ROLES> rp = service.getRolesByNS(trans, ns);
+ switch(rp.status) {
+ case OK:
+ if(!rp.isEmpty()) {
+ RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ } else {
+ Question.logEncryptTrace(trans, NO_DATA);
+ }
+ setContentType(resp,roleDF.getOutType());
+ 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 org.onap.aaf.authz.facade.AuthzFacade#getRolesByNameOnly(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getRolesByNameOnly(AuthzTrans trans,HttpServletResponse resp, String nameOnly) {
+ TimeTaken tt = trans.start(GET_ROLES_BY_NAME_ONLY + ' ' + nameOnly, Env.SUB|Env.ALWAYS);
+ try {
+ Result<ROLES> rp = service.getRolesByNameOnly(trans, nameOnly);
+ switch(rp.status) {
+ case OK:
+ if(!rp.isEmpty()) {
+ RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ } else {
+ Question.logEncryptTrace(trans, NO_DATA);
+ }
+ setContentType(resp,roleDF.getOutType());
+ 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 org.onap.aaf.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getRolesByPerm(AuthzTrans trans,HttpServletResponse resp, String type, String instance, String action) {
+ TimeTaken tt = trans.start(GET_ROLES_BY_PERM + type +' '+instance+' '+action, Env.SUB|Env.ALWAYS);
+ try {
+ Result<ROLES> rp = service.getRolesByPerm(trans, type,instance,action);
+ switch(rp.status) {
+ case OK:
+ RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,roleDF.getOutType());
+ 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 org.onap.aaf.authz.facade.AuthzFacade#updateDescription(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ @Override
+ public Result<Void> updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(UPDATE_ROLE_DESC, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = roleRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,UPDATE_ROLE_DESC);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+
+ }
+ Result<Void> rp = service.updateRoleDescription(trans, rreq);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,roleRequestDF.getOutType());
+ return Result.ok();
+ default:
+ return rp;
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,UPDATE_ROLE_DESC);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> addPermToRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(ADD_PERM_TO_ROLE, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = rolePermRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,ADD_PERM_TO_ROLE);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+
+ }
+ Result<Void> rp = service.addPermToRole(trans, rreq);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ resp.getOutputStream().println();
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,ADD_PERM_TO_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> delPermFromRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(DELETE_PERM_FROM_ROLE, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = rolePermRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,DELETE_PERM_FROM_ROLE);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+
+ }
+ Result<Void> rp = service.delPermFromRole(trans, rreq);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ resp.getOutputStream().println();
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_PERM_FROM_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> deleteRole(AuthzTrans trans, HttpServletResponse resp, String role) {
+ TimeTaken tt = trans.start(DELETE_ROLE + ' ' + role, Env.SUB|Env.ALWAYS);
+ try {
+ Result<Void> rp = service.deleteRole(trans, role);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(DELETE_ROLE, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = roleRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN,CREATE_ROLE);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+ }
+
+ Result<Void> rp = service.deleteRole(trans, rreq);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ public static final String CREATE_CRED = "createUserCred";
+ private static final String GET_CREDS_BY_NS = "getCredsByNS";
+ private static final String GET_CREDS_BY_ID = "getCredsByID";
+ public static final String UPDATE_CRED = "updateUserCred";
+ public static final String EXTEND_CRED = "extendUserCred";
+ public static final String DELETE_CRED = "deleteUserCred";
+ public static final String DOES_CRED_MATCH = "doesCredMatch";
+ public static final String VALIDATE_BASIC_AUTH = "validateBasicAuth";
+
+
+
+ @Override
+ /**
+ * Create Credential
+ *
+ */
+ public Result<Void> createUserCred(AuthzTrans trans, HttpServletRequest req) {
+ TimeTaken tt = trans.start(CREATE_CRED, Env.SUB|Env.ALWAYS);
+ try {
+ RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ return service.createUserCred(trans, data.asObject());
+ } catch(APIException e) {
+ trans.error().log(e,"Bad Input data");
+ return Result.err(Status.ERR_BadData, e.getLocalizedMessage());
+ } catch (Exception e) {
+ trans.error().log(e,IN,CREATE_CRED);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> changeUserCred(AuthzTrans trans, HttpServletRequest req) {
+ TimeTaken tt = trans.start(UPDATE_CRED, Env.SUB|Env.ALWAYS);
+ try {
+ RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ return service.changeUserCred(trans, data.asObject());
+ } catch(APIException e) {
+ trans.error().log(e,"Bad Input data");
+ return Result.err(Status.ERR_BadData, e.getLocalizedMessage());
+ } catch (Exception e) {
+ trans.error().log(e,IN,UPDATE_CRED);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#extendUserCred(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, int)
+ */
+ @Override
+ public Result<Void> extendUserCred(AuthzTrans trans, HttpServletRequest req, String days) {
+ TimeTaken tt = trans.start(EXTEND_CRED, Env.SUB|Env.ALWAYS);
+ try {
+ RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ return service.extendUserCred(trans, data.asObject(), days);
+ } catch(APIException e) {
+ trans.error().log(e,"Bad Input data");
+ return Result.err(Status.ERR_BadData, e.getLocalizedMessage());
+ } catch (Exception e) {
+ trans.error().log(e,IN,EXTEND_CRED);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns) {
+ TimeTaken tt = trans.start(GET_CREDS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS);
+
+ try {
+ Result<USERS> ru = service.getCredsByNS(trans,ns);
+ switch(ru.status) {
+ case OK:
+ RosettaData<USERS> data = usersDF.newData(trans).load(ru.value);
+ if(Question.willSpecialLog(trans,trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,usersDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(ru);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_CREDS_BY_NS);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getCredsByID(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id) {
+ TimeTaken tt = trans.start(GET_CREDS_BY_ID + ' ' + id, Env.SUB|Env.ALWAYS);
+
+ try {
+ Result<USERS> ru = service.getCredsByID(trans,id);
+ switch(ru.status) {
+ case OK:
+ RosettaData<USERS> data = usersDF.newData(trans).load(ru.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,usersDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(ru);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_CREDS_BY_ID);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+
+ }
+
+ @Override
+ public Result<Void> deleteUserCred(AuthzTrans trans, HttpServletRequest req) {
+ TimeTaken tt = trans.start(DELETE_CRED, Env.SUB|Env.ALWAYS);
+ try {
+ RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ return service.deleteUserCred(trans, data.asObject());
+ } catch(APIException e) {
+ trans.error().log(e,"Bad Input data");
+ return Result.err(Status.ERR_BadData, e.getLocalizedMessage());
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_CRED);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+
+ @Override
+ public Result<Date> doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(DOES_CRED_MATCH, Env.SUB|Env.ALWAYS);
+ try {
+ RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ return service.doesCredentialMatch(trans, data.asObject());
+ } catch(APIException e) {
+ trans.error().log(e,"Bad Input data");
+ return Result.err(Status.ERR_BadData, e.getLocalizedMessage());
+ } catch (IOException e) {
+ trans.error().log(e,IN,DOES_CRED_MATCH);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+
+ @Override
+ public Result<Void> validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth) {
+ TimeTaken tt = trans.start(VALIDATE_BASIC_AUTH, Env.SUB|Env.ALWAYS);
+ try {
+ Result<Date> result = service.validateBasicAuth(trans,basicAuth);
+ switch(result.status){
+ case OK:
+ resp.getOutputStream().write(Chrono.utcStamp(result.value).getBytes());
+ return Result.ok();
+ }
+ return Result.err(result);
+ } catch (Exception e) {
+ trans.error().log(e,IN,VALIDATE_BASIC_AUTH);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getCertInfoByID(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id) {
+ TimeTaken tt = trans.start(GET_CERT_BY_ID, Env.SUB|Env.ALWAYS);
+ try {
+ Result<CERTS> rci = service.getCertInfoByID(trans,req,id);
+
+ switch(rci.status) {
+ case OK:
+ if(Question.willSpecialLog(trans, trans.user())) {
+ RosettaData<CERTS> data = certsDF.newData(trans).load(rci.value);
+ Question.logEncryptTrace(trans,data.asString());
+ data.to(resp.getOutputStream());
+ } else {
+ certsDF.direct(trans, rci.value, resp.getOutputStream());
+ }
+ setContentType(resp,certsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rci);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_CERT_BY_ID);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ public static final String CREATE_DELEGATE = "createDelegate";
+ public static final String UPDATE_DELEGATE = "updateDelegate";
+ public static final String DELETE_DELEGATE = "deleteDelegate";
+ public static final String GET_DELEGATE_USER = "getDelegatesByUser";
+ public static final String GET_DELEGATE_DELG = "getDelegatesByDelegate";
+
+ @Override
+ public Result<Void> createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(CREATE_DELEGATE, Env.SUB|Env.ALWAYS);
+ try {
+ Data<REQUEST> data = delgRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ return service.createDelegate(trans, data.asObject());
+ } catch (Exception e) {
+ trans.error().log(e,IN,CREATE_DELEGATE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(UPDATE_DELEGATE, Env.SUB|Env.ALWAYS);
+ try {
+ Data<REQUEST> data = delgRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ return service.updateDelegate(trans, data.asObject());
+ } catch (Exception e) {
+ trans.error().log(e,IN,UPDATE_DELEGATE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(DELETE_DELEGATE, Env.SUB|Env.ALWAYS);
+ try {
+ Data<REQUEST> data = delgRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ return service.deleteDelegate(trans, data.asObject());
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_DELEGATE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> deleteDelegate(AuthzTrans trans, String userName) {
+ TimeTaken tt = trans.start(DELETE_DELEGATE + ' ' + userName, Env.SUB|Env.ALWAYS);
+ try {
+ return service.deleteDelegate(trans, userName);
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_DELEGATE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> getDelegatesByUser(AuthzTrans trans, String user, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(GET_DELEGATE_USER, Env.SUB|Env.ALWAYS);
+ try {
+ Result<DELGS> rd = service.getDelegatesByUser(trans, user);
+
+ switch(rd.status) {
+ case OK:
+ RosettaData<DELGS> data = delgDF.newData(trans).load(rd.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,delgDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rd);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_DELEGATE_USER);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> getDelegatesByDelegate(AuthzTrans trans, String delegate, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(GET_DELEGATE_DELG, Env.SUB|Env.ALWAYS);
+ try {
+ Result<DELGS> rd = service.getDelegatesByDelegate(trans, delegate);
+ switch(rd.status) {
+ case OK:
+ RosettaData<DELGS> data = delgDF.newData(trans).load(rd.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+ setContentType(resp,delgDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rd);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_DELEGATE_DELG);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ private static final String REQUEST_USER_ROLE = "createUserRole";
+ private static final String GET_USERROLES = "getUserRoles";
+ private static final String GET_USERROLES_BY_ROLE = "getUserRolesByRole";
+ private static final String GET_USERROLES_BY_USER = "getUserRolesByUser";
+ private static final String SET_ROLES_FOR_USER = "setRolesForUser";
+ private static final String SET_USERS_FOR_ROLE = "setUsersForRole";
+ private static final String EXTEND_USER_ROLE = "extendUserRole";
+ private static final String DELETE_USER_ROLE = "deleteUserRole";
+ @Override
+ public Result<Void> requestUserRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(REQUEST_USER_ROLE, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST request;
+ try {
+ Data<REQUEST> data = userRoleRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ request = data.asObject();
+ } catch(APIException e) {
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+ }
+
+ Result<Void> rp = service.createUserRole(trans,request);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,REQUEST_USER_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) {
+ TimeTaken tt = trans.start(GET_USERROLES + ' ' + user + '|' + role, Env.SUB|Env.ALWAYS);
+ try {
+ Result<USERS> ru = service.getUserInRole(trans,user,role);
+ switch(ru.status) {
+ case OK:
+ RosettaData<USERS> data = usersDF.newData(trans).load(ru.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,usersDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(ru);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_USERROLES);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+
+ }
+
+ @Override
+ public Result<Void> getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user) {
+ TimeTaken tt = trans.start(GET_USERROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS);
+ try {
+ Result<USERROLES> ru = service.getUserRolesByUser(trans,user);
+ switch(ru.status) {
+ case OK:
+ RosettaData<USERROLES> data = userrolesDF.newData(trans).load(ru.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,usersDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(ru);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_USERROLES_BY_USER);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+
+ }
+
+ @Override
+ public Result<Void> getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role) {
+ TimeTaken tt = trans.start(GET_USERROLES_BY_ROLE + ' ' + role, Env.SUB|Env.ALWAYS);
+ try {
+ Result<USERROLES> ru = service.getUserRolesByRole(trans,role);
+ switch(ru.status) {
+ case OK:
+ RosettaData<USERROLES> data = userrolesDF.newData(trans).load(ru.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,usersDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(ru);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_USERROLES_BY_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+
+ }
+
+
+ @Override
+ public Result<Void> resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) {
+ TimeTaken tt = trans.start(SET_USERS_FOR_ROLE, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = userRoleRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN, SET_USERS_FOR_ROLE);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+ }
+
+ Result<Void> rp = service.resetUsersForRole(trans, rreq);
+
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,SET_USERS_FOR_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+
+ }
+
+ @Override
+ public Result<Void> resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) {
+ TimeTaken tt = trans.start(SET_ROLES_FOR_USER, Env.SUB|Env.ALWAYS);
+ try {
+ REQUEST rreq;
+ try {
+ RosettaData<REQUEST> data = userRoleRequestDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ rreq = data.asObject();
+ } catch(APIException e) {
+ trans.error().log("Invalid Input",IN, SET_ROLES_FOR_USER);
+ return Result.err(Status.ERR_BadData,"Invalid Input");
+ }
+
+ Result<Void> rp = service.resetRolesForUser(trans, rreq);
+
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,SET_ROLES_FOR_USER);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#extendUserRoleExpiration(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, String role) {
+ TimeTaken tt = trans.start(EXTEND_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS);
+ try {
+ return service.extendUserRole(trans,user,role);
+ } catch (Exception e) {
+ trans.error().log(e,IN,EXTEND_USER_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) {
+ TimeTaken tt = trans.start(DELETE_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS);
+ try {
+ Result<Void> rp = service.deleteUserRole(trans,user,role);
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,DELETE_USER_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ private static final String UPDATE_APPROVAL = "updateApproval";
+ private static final String GET_APPROVALS_BY_USER = "getApprovalsByUser.";
+ private static final String GET_APPROVALS_BY_TICKET = "getApprovalsByTicket.";
+ private static final String GET_APPROVALS_BY_APPROVER = "getApprovalsByApprover.";
+
+ @Override
+ public Result<Void> updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
+ TimeTaken tt = trans.start(UPDATE_APPROVAL, Env.SUB|Env.ALWAYS);
+ try {
+ Data<APPROVALS> data = approvalDF.newData().load(req.getInputStream());
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ Result<Void> rp = service.updateApproval(trans, data.asObject());
+
+ switch(rp.status) {
+ case OK:
+ setContentType(resp,approvalDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,UPDATE_APPROVAL);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user) {
+ TimeTaken tt = trans.start(GET_APPROVALS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS);
+ try {
+ Result<APPROVALS> rp = service.getApprovalsByUser(trans, user);
+ switch(rp.status) {
+ case OK:
+ RosettaData<APPROVALS> data = approvalDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+ data.to(resp.getOutputStream());
+
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_APPROVALS_BY_USER, user);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver) {
+ TimeTaken tt = trans.start(GET_APPROVALS_BY_APPROVER + ' ' + approver, Env.SUB|Env.ALWAYS);
+ try {
+ Result<APPROVALS> rp = service.getApprovalsByApprover(trans, approver);
+ switch(rp.status) {
+ case OK:
+ RosettaData<APPROVALS> data = approvalDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_APPROVALS_BY_APPROVER,approver);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<Void> getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket) {
+ TimeTaken tt = trans.start(GET_APPROVALS_BY_TICKET, Env.SUB|Env.ALWAYS);
+ try {
+ Result<APPROVALS> rp = service.getApprovalsByTicket(trans, ticket);
+ switch(rp.status) {
+ case OK:
+ RosettaData<APPROVALS> data = approvalDF.newData(trans).load(rp.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,permsDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rp);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_APPROVALS_BY_TICKET);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+
+
+ public static final String GET_USERS_PERMISSION = "getUsersByPermission";
+ public static final String GET_USERS_ROLE = "getUsersByRole";
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getUsersByRole(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role) {
+ TimeTaken tt = trans.start(GET_USERS_ROLE + ' ' + role, Env.SUB|Env.ALWAYS);
+ try {
+ Result<USERS> ru = service.getUsersByRole(trans,role);
+ switch(ru.status) {
+ case OK:
+ RosettaData<USERS> data = usersDF.newData(trans).load(ru.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,usersDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(ru);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_USERS_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getUsersByPermission(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String)
+ */
+ @Override
+ public Result<Void> getUsersByPermission(AuthzTrans trans, HttpServletResponse resp,
+ String type, String instance, String action) {
+ TimeTaken tt = trans.start(GET_USERS_PERMISSION + ' ' + type + ' ' + instance + ' ' +action, Env.SUB|Env.ALWAYS);
+ try {
+ Result<USERS> ru = service.getUsersByPermission(trans,type,instance,action);
+ switch(ru.status) {
+ case OK:
+ RosettaData<USERS> data = usersDF.newData(trans).load(ru.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,usersDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(ru);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_USERS_PERMISSION);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+
+ public static final String GET_HISTORY_USER = "getHistoryByUser";
+ public static final String GET_HISTORY_ROLE = "getHistoryByRole";
+ public static final String GET_HISTORY_PERM = "getHistoryByPerm";
+ public static final String GET_HISTORY_NS = "getHistoryByNS";
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getHistoryByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ @Override
+ public Result<Void> getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(GET_HISTORY_USER);
+ sb.append(' ');
+ sb.append(user);
+ sb.append(" for ");
+ boolean first = true;
+ for(int i : yyyymm) {
+ if(first) {
+ first = false;
+ } else {
+ sb.append(',');
+ }
+ sb.append(i);
+ }
+ TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS);
+
+ try {
+ Result<HISTORY> rh = service.getHistoryByUser(trans,user,yyyymm,sort);
+ switch(rh.status) {
+ case OK:
+ RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,historyDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rh);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_HISTORY_USER);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getHistoryByRole(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[])
+ */
+ @Override
+ public Result<Void> getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String role, int[] yyyymm, final int sort) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(GET_HISTORY_ROLE);
+ sb.append(' ');
+ sb.append(role);
+ sb.append(" for ");
+ boolean first = true;
+ for(int i : yyyymm) {
+ if(first) {
+ first = false;
+ } else {
+ sb.append(',');
+ }
+ sb.append(i);
+ }
+ TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS);
+ try {
+ Result<HISTORY> rh = service.getHistoryByRole(trans,role,yyyymm,sort);
+ switch(rh.status) {
+ case OK:
+ RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,historyDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rh);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_HISTORY_ROLE);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getHistoryByNS(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[])
+ */
+ @Override
+ public Result<Void> getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String ns, int[] yyyymm, final int sort) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(GET_HISTORY_NS);
+ sb.append(' ');
+ sb.append(ns);
+ sb.append(" for ");
+ boolean first = true;
+ for(int i : yyyymm) {
+ if(first) {
+ first = false;
+ } else {
+ sb.append(',');
+ }
+ sb.append(i);
+ }
+ TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS);
+ try {
+ Result<HISTORY> rh = service.getHistoryByNS(trans,ns,yyyymm,sort);
+ switch(rh.status) {
+ case OK:
+ RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,historyDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rh);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_HISTORY_NS);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getHistoryByPerm(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[])
+ */
+ @Override
+ public Result<Void> getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String perm, int[] yyyymm, final int sort) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(GET_HISTORY_PERM);
+ sb.append(' ');
+ sb.append(perm);
+ sb.append(" for ");
+ boolean first = true;
+ for(int i : yyyymm) {
+ if(first) {
+ first = false;
+ } else {
+ sb.append(',');
+ }
+ sb.append(i);
+ }
+ TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS);
+ try {
+ Result<HISTORY> rh = service.getHistoryByPerm(trans,perm,yyyymm,sort);
+ switch(rh.status) {
+ case OK:
+ RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,historyDF.getOutType());
+ return Result.ok();
+ default:
+ return Result.err(rh);
+ }
+ } catch (Exception e) {
+ trans.error().log(e,IN,GET_HISTORY_PERM);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ public final static String CACHE_CLEAR = "cacheClear ";
+// public final static String CACHE_VALIDATE = "validateCache";
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#cacheClear(org.onap.aaf.authz.env.AuthzTrans, java.lang.String)
+ */
+ @Override
+ public Result<Void> cacheClear(AuthzTrans trans, String cname) {
+ TimeTaken tt = trans.start(CACHE_CLEAR + cname, Env.SUB|Env.ALWAYS);
+ try {
+ return service.cacheClear(trans,cname);
+ } catch (Exception e) {
+ trans.error().log(e,IN,CACHE_CLEAR);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#cacheClear(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.Integer)
+ */
+ @Override
+ public Result<Void> cacheClear(AuthzTrans trans, String cname, String segments) {
+ TimeTaken tt = trans.start(CACHE_CLEAR + cname + ", segments[" + segments + ']', Env.SUB|Env.ALWAYS);
+ try {
+ String[] segs = segments.split("\\s*,\\s*");
+ int isegs[] = new int[segs.length];
+ for(int i=0;i<segs.length;++i) {
+ try {
+ isegs[i] = Integer.parseInt(segs[i]);
+ } catch(NumberFormatException nfe) {
+ isegs[i] = -1;
+ }
+ }
+ return service.cacheClear(trans,cname, isegs);
+ } catch (Exception e) {
+ trans.error().log(e,IN,CACHE_CLEAR);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#dbReset(org.onap.aaf.authz.env.AuthzTrans)
+ */
+ @Override
+ public void dbReset(AuthzTrans trans) {
+ service.dbReset(trans);
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getAPI(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse)
+ */
+ public final static String API_REPORT = "apiReport";
+ @Override
+ public Result<Void> getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet<AuthzTrans> rservlet) {
+ TimeTaken tt = trans.start(API_REPORT, Env.SUB);
+ try {
+ Api api = new Api();
+ Api.Route ar;
+ Method[] meths = AuthzCassServiceImpl.class.getDeclaredMethods();
+ for(RouteReport rr : rservlet.routeReport()) {
+ api.getRoute().add(ar = new Api.Route());
+ ar.setMeth(rr.meth.name());
+ ar.setPath(rr.path);
+ ar.setDesc(rr.desc);
+ ar.getContentType().addAll(rr.contextTypes);
+ for(Method m : meths) {
+ ApiDoc ad;
+ if((ad = m.getAnnotation(ApiDoc.class))!=null &&
+ rr.meth.equals(ad.method()) &&
+ rr.path.equals(ad.path())) {
+ for(String param : ad.params()) {
+ ar.getParam().add(param);
+ }
+ for(String text : ad.text()) {
+ ar.getComments().add(text);
+ }
+ ar.setExpected(ad.expectedCode());
+ for(int ec : ad.errorCodes()) {
+ ar.getExplicitErr().add(ec);
+ }
+ }
+ }
+ }
+ RosettaData<Api> data = apiDF.newData(trans).load(api);
+ if(Question.willSpecialLog(trans, trans.user())) {
+ Question.logEncryptTrace(trans,data.asString());
+ }
+
+ data.to(resp.getOutputStream());
+ setContentType(resp,apiDF.getOutType());
+ return Result.ok();
+
+ } catch (Exception e) {
+ trans.error().log(e,IN,API_REPORT);
+ return Result.err(e);
+ } finally {
+ tt.done();
+ }
+ }
+
+
+ public final static String API_EXAMPLE = "apiExample";
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.facade.AuthzFacade#getAPIExample(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ @Override
+ public Result<Void> getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) {
+ TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB);
+ try {
+ String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional);
+ resp.getOutputStream().print(content);
+ setContentType(resp,content.contains("<?xml")?TYPE.XML:TYPE.JSON);
+ return Result.ok();
+ } catch (Exception e) {
+ trans.error().log(e,IN,API_EXAMPLE);
+ return Result.err(Status.ERR_NotImplemented,e.getMessage());
+ } finally {
+ tt.done();
+ }
+ }
+
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacade_2_0.java b/authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacade_2_0.java new file mode 100644 index 00000000..fae128cf --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacade_2_0.java @@ -0,0 +1,65 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.facade;
+
+import org.onap.aaf.authz.env.AuthzEnv;
+import org.onap.aaf.authz.service.AuthzService;
+
+import org.onap.aaf.inno.env.APIException;
+import org.onap.aaf.inno.env.Data;
+
+import aaf.v2_0.Approvals;
+import aaf.v2_0.Certs;
+import aaf.v2_0.Delgs;
+import aaf.v2_0.Error;
+import aaf.v2_0.History;
+import aaf.v2_0.Keys;
+import aaf.v2_0.Nss;
+import aaf.v2_0.Perms;
+import aaf.v2_0.Pkey;
+import aaf.v2_0.Request;
+import aaf.v2_0.Roles;
+import aaf.v2_0.UserRoles;
+import aaf.v2_0.Users;
+
+public class AuthzFacade_2_0 extends AuthzFacadeImpl<
+ Nss,
+ Perms,
+ Pkey,
+ Roles,
+ Users,
+ UserRoles,
+ Delgs,
+ Certs,
+ Keys,
+ Request,
+ History,
+ Error,
+ Approvals>
+{
+ public AuthzFacade_2_0(AuthzEnv env,
+ AuthzService<Nss, Perms, Pkey, Roles, Users, UserRoles, Delgs, Certs, Keys, Request, History, Error, Approvals> service,
+ Data.TYPE type) throws APIException {
+ super(env, service, type);
+ }
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/AuthAPI.java b/authz-service/src/main/java/org/onap/aaf/authz/service/AuthAPI.java new file mode 100644 index 00000000..3a918072 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/AuthAPI.java @@ -0,0 +1,330 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.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 org.onap.aaf.authz.cadi.DirectAAFLur;
+import org.onap.aaf.authz.cadi.DirectAAFUserPass;
+import org.onap.aaf.authz.cadi.DirectCertIdentity;
+import org.onap.aaf.authz.env.AuthzEnv;
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.env.AuthzTransFilter;
+import org.onap.aaf.authz.facade.AuthzFacadeFactory;
+import org.onap.aaf.authz.facade.AuthzFacade_2_0;
+import org.onap.aaf.authz.org.OrganizationFactory;
+import org.onap.aaf.authz.server.AbsServer;
+import org.onap.aaf.authz.service.api.API_Api;
+import org.onap.aaf.authz.service.api.API_Approval;
+import org.onap.aaf.authz.service.api.API_Creds;
+import org.onap.aaf.authz.service.api.API_Delegate;
+import org.onap.aaf.authz.service.api.API_History;
+import org.onap.aaf.authz.service.api.API_Mgmt;
+import org.onap.aaf.authz.service.api.API_NS;
+import org.onap.aaf.authz.service.api.API_Perms;
+import org.onap.aaf.authz.service.api.API_Roles;
+import org.onap.aaf.authz.service.api.API_User;
+import org.onap.aaf.authz.service.api.API_UserRole;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+import org.onap.aaf.cssa.rserv.HttpMethods;
+import org.onap.aaf.dao.CassAccess;
+import org.onap.aaf.dao.aaf.cass.CacheInfoDAO;
+import org.onap.aaf.dao.aaf.hl.Question;
+
+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 org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.aaf.v2_0.AAFTrustChecker;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.config.SecurityInfoC;
+import org.onap.aaf.cadi.http.HBasicAuthSS;
+import org.onap.aaf.cadi.http.HMangr;
+import org.onap.aaf.cadi.http.HX509SS;
+import org.onap.aaf.cadi.locator.DME2Locator;
+import org.onap.aaf.cadi.taf.basic.BasicHttpTaf;
+import org.onap.aaf.inno.env.APIException;
+import org.onap.aaf.inno.env.Data;
+import org.onap.aaf.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 = org.onap.aaf.dao.CassAccess.cluster(env,null);
+
+ // jg 4/2015 SessionFilter unneeded... DataStax already deals with Multithreading well
+
+ // Setup Shutdown Hooks for Cluster and Pooled Sessions
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ @Override
+ public void run() {
+// sessionFilter.destroy();
+ cluster.close();
+ }
+ });
+
+ // Initialize Facade for all uses
+ AuthzTrans trans = env.newTrans();
+
+ // Initialize Organizations... otherwise, first pass may miss
+ int org_size = ORGANIZATION.length();
+ for(String n : env.existingStaticSlotNames()) {
+ if(n.startsWith(ORGANIZATION)) {
+ OrganizationFactory.obtain(env, n.substring(org_size));
+ }
+ }
+
+ // Need Question for Security purposes (direct User/Authz Query in Filter)
+ // Start Background Processing
+ question = new Question(trans, cluster, CassAccess.KEYSPACE, true);
+
+ DirectCertIdentity.set(question.certDAO);
+
+ facade = AuthzFacadeFactory.v2_0(env,trans,Data.TYPE.JSON,question);
+ facade_XML = AuthzFacadeFactory.v2_0(env,trans,Data.TYPE.XML,question);
+
+ directAAFUserPass = new DirectAAFUserPass(
+ trans.env(),question,trans.getProperty("Unknown"));
+
+
+ // Print results and cleanup
+ StringBuilder sb = new StringBuilder();
+ trans.auditTrail(0, sb);
+ if(sb.length()>0)env.init().log(sb);
+ trans = null;
+ sb = null;
+
+ ////////////////////////////////////////////////////////////////////////////
+ // Time Critical
+ // These will always be evaluated first
+ ////////////////////////////////////////////////////////////////////////
+ API_Creds.timeSensitiveInit(env, this, facade,directAAFUserPass);
+ API_Perms.timeSensitiveInit(this, facade);
+ ////////////////////////////////////////////////////////////////////////
+ // Service APIs
+ ////////////////////////////////////////////////////////////////////////
+ API_Creds.init(this, facade);
+ API_UserRole.init(this, facade);
+ API_Roles.init(this, facade);
+ API_Perms.init(this, facade);
+ API_NS.init(this, facade);
+ API_User.init(this, facade);
+ API_Delegate.init(this,facade);
+ API_Approval.init(this, facade);
+ API_History.init(this, facade);
+
+ ////////////////////////////////////////////////////////////////////////
+ // Management APIs
+ ////////////////////////////////////////////////////////////////////////
+ // There are several APIs around each concept, and it gets a bit too
+ // long in this class to create. The initialization of these Management
+ // APIs have therefore been pushed to StandAlone Classes with static
+ // init functions
+ API_Mgmt.init(this, facade);
+ API_Api.init(this, facade);
+
+ }
+
+ /**
+ * Setup XML and JSON implementations for each supported Version type
+ *
+ * We do this by taking the Code passed in and creating clones of these with the appropriate Facades and properties
+ * to do Versions and Content switches
+ *
+ */
+ public void route(HttpMethods meth, String path, API api, Code code) throws Exception {
+ String version = "2.0";
+ Class<?> respCls = facade.mapper().getClass(api);
+ if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name());
+ String application = applicationJSON(respCls, version);
+
+ route(env,meth,path,code,application,"application/json;version=2.0","*/*");
+ application = applicationXML(respCls, version);
+ route(env,meth,path,code.clone(facade_XML,false),application,"text/xml;version=2.0");
+ }
+
+ /**
+ * Start up AuthzAPI as DME2 Service
+ * @param env
+ * @param props
+ * @throws Exception
+ * @throws LocatorException
+ * @throws CadiException
+ * @throws NumberFormatException
+ * @throws IOException
+ * @throws GeneralSecurityException
+ * @throws APIException
+ */
+ public void startDME2(Properties props) throws Exception {
+ DME2Manager dme2 = new DME2Manager("AuthzServiceDME2Manager",props);
+ String s = dme2.getStringProp(Config.AFT_DME2_SSL_INCLUDE_PROTOCOLS,null);
+ env.init().log("DME2 Service TLS Protocols are set to",(s==null?"DME2 Default":s));
+
+ DME2ServiceHolder svcHolder;
+ List<DME2ServletHolder> slist = new ArrayList<DME2ServletHolder>();
+ svcHolder = new DME2ServiceHolder();
+ String serviceName = env.getProperty("DMEServiceName",null);
+ if(serviceName!=null) {
+ svcHolder.setServiceURI(serviceName);
+ svcHolder.setManager(dme2);
+ svcHolder.setContext("/");
+ DME2ServletHolder srvHolder = new DME2ServletHolder(this, new String[]{"/authz","/authn","/mgmt"});
+ srvHolder.setContextPath("/*");
+ slist.add(srvHolder);
+
+ EnumSet<RequestDispatcherType> edlist = EnumSet.of(
+ RequestDispatcherType.REQUEST,
+ RequestDispatcherType.FORWARD,
+ RequestDispatcherType.ASYNC
+ );
+
+ List<DME2FilterHolder> flist = new ArrayList<DME2FilterHolder>();
+
+ // Add DME2 Metrics
+ // DME2 removed the Metrics Filter in 2.8.8.5
+ // flist.add(new DME2FilterHolder(new DME2MetricsFilter(serviceName),"/*",edlist));
+
+ // Note: Need CADI to fill out User for AuthTransFilter... so it's first
+ // Make sure there is no AAF TAF configured for Filters
+ env.setProperty(Config.AAF_URL,null);
+
+ flist.add(
+ new DME2FilterHolder(
+ new AuthzTransFilter(env, null /* no connection to AAF... it is AAF */,
+ new AAFTrustChecker((Env)env),
+ new DirectAAFLur(env,question), // Note, this will be assigned by AuthzTransFilter to TrustChecker
+ new BasicHttpTaf(env, directAAFUserPass,
+ DOMAIN,Long.parseLong(env.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)),
+ false
+ ) // Add specialty Direct TAF
+ ),
+ "/*", edlist));
+
+ svcHolder.setFilters(flist);
+ svcHolder.setServletHolders(slist);
+
+ DME2Server dme2svr = dme2.getServer();
+
+ String hostname = env.getProperty("HOSTNAME",null);
+ if(hostname!=null) {
+ //dme2svr.setHostname(hostname);
+ hostname=null;
+ }
+ // dme2svr.setGracefulShutdownTimeMs(5000);
+
+ env.init().log("Starting AAF Jetty/DME2 server...");
+ dme2svr.start();
+ try {
+// if(env.getProperty("NO_REGISTER",null)!=null)
+ dme2.bindService(svcHolder);
+ //env.init().log("DME2 is available as HTTPS on port:",dme2svr.getPort());
+
+ // Start CacheInfo Listener
+ HMangr hman = new HMangr(env, new DME2Locator(env, dme2,"https://DME2RESOLVE/"+serviceName,true /*remove self from cache*/));
+ SecuritySetter<HttpURLConnection> ss;
+
+// InetAddress ip = InetAddress.getByName(dme2svr.getHostname());
+ SecurityInfoC<HttpURLConnection> si = new SecurityInfoC<HttpURLConnection>(env);
+ String mechID;
+ if((mechID=env.getProperty(Config.AAF_MECHID))==null) {
+ String alias = env.getProperty(Config.CADI_ALIAS);
+ if(alias==null) {
+ env.init().log(Config.CADI_ALIAS, "is required for AAF Authentication by Certificate. Alternately, set",Config.AAF_MECHID,"and",Config.AAF_MECHPASS);
+ System.exit(1);
+ }
+ ss = new HX509SS(alias,si,true);
+ env.init().log("X509 Certificate Client configured:", alias);
+ } else {
+ String pass = env.getProperty(Config.AAF_MECHPASS);
+ if(pass==null) {
+ env.init().log(Config.AAF_MECHPASS, "is required for AAF Authentication by ID/Pass");
+ System.exit(1);
+ }
+ ss = new HBasicAuthSS(mechID,env.decrypt(pass, true),si,true);
+ env.init().log("BasicAuth (ID/Pass) Client configured.");
+ }
+
+ //TODO Reenable Cache Update
+ //CacheInfoDAO.startUpdate(env, hman, ss, dme2svr.getHostname(), dme2svr.getPort());
+
+ while(true) { // Per DME2 Examples...
+ Thread.sleep(5000);
+ }
+ } catch(DME2Exception e) { // Error binding service doesn't seem to stop DME2 or Process
+ env.init().log(e,"DME2 Initialization Error");
+ dme2svr.stop();
+ System.exit(1);
+ } catch(InterruptedException e) {
+ env.init().log("AAF Jetty Server interrupted!");
+ }
+ } else {
+ env.init().log("Properties must contain 'DMEServiceName'");
+ }
+ }
+
+ public static void main(String[] args) {
+ setup(AuthAPI.class,"authAPI.props");
+ }
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/AuthzCassServiceImpl.java b/authz-service/src/main/java/org/onap/aaf/authz/service/AuthzCassServiceImpl.java new file mode 100644 index 00000000..13884747 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/AuthzCassServiceImpl.java @@ -0,0 +1,3973 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+import static org.onap.aaf.cssa.rserv.HttpMethods.DELETE;
+import static org.onap.aaf.cssa.rserv.HttpMethods.GET;
+import static org.onap.aaf.cssa.rserv.HttpMethods.POST;
+import static org.onap.aaf.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 org.onap.aaf.authz.common.Define;
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.org.Executor;
+import org.onap.aaf.authz.org.Organization;
+import org.onap.aaf.authz.org.Organization.Expiration;
+import org.onap.aaf.authz.org.Organization.Identity;
+import org.onap.aaf.authz.org.Organization.Policy;
+import org.onap.aaf.authz.service.mapper.Mapper;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+import org.onap.aaf.authz.service.validation.Validator;
+import org.onap.aaf.cssa.rserv.doc.ApiDoc;
+import org.onap.aaf.dao.DAOException;
+import org.onap.aaf.dao.aaf.cass.ApprovalDAO;
+import org.onap.aaf.dao.aaf.cass.CertDAO;
+import org.onap.aaf.dao.aaf.cass.CredDAO;
+import org.onap.aaf.dao.aaf.cass.DelegateDAO;
+import org.onap.aaf.dao.aaf.cass.FutureDAO;
+import org.onap.aaf.dao.aaf.cass.HistoryDAO;
+import org.onap.aaf.dao.aaf.cass.Namespace;
+import org.onap.aaf.dao.aaf.cass.NsDAO;
+import org.onap.aaf.dao.aaf.cass.NsSplit;
+import org.onap.aaf.dao.aaf.cass.NsType;
+import org.onap.aaf.dao.aaf.cass.PermDAO;
+import org.onap.aaf.dao.aaf.cass.RoleDAO;
+import org.onap.aaf.dao.aaf.cass.Status;
+import org.onap.aaf.dao.aaf.cass.UserRoleDAO;
+import org.onap.aaf.dao.aaf.cass.NsDAO.Data;
+import org.onap.aaf.dao.aaf.hl.CassExecutor;
+import org.onap.aaf.dao.aaf.hl.Function;
+import org.onap.aaf.dao.aaf.hl.Question;
+import org.onap.aaf.dao.aaf.hl.Question.Access;
+
+import org.onap.aaf.cadi.principal.BasicPrincipal;
+import org.onap.aaf.inno.env.Env;
+import org.onap.aaf.inno.env.TimeTaken;
+import org.onap.aaf.inno.env.util.Chrono;
+import org.onap.aaf.inno.env.util.Split;
+
+import aaf.v2_0.CredRequest;
+
+/**
+ * AuthzCassServiceImpl implements AuthzCassService for
+ *
+ *
+ * @param <NSS>
+ * @param <PERMS>
+ * @param <PERMKEY>
+ * @param <ROLES>
+ * @param <USERS>
+ * @param <DELGS>
+ * @param <REQUEST>
+ * @param <HISTORY>
+ * @param <ERR>
+ * @param <APPROVALS>
+ */
+public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS>
+ implements AuthzService <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> {
+
+ private Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper;
+ @Override
+ public Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper() {return mapper;}
+
+ private static final String ASTERIX = "*";
+ private static final String CACHE = "cache";
+
+ private final Question ques;
+ private final Function func;
+
+ public AuthzCassServiceImpl(AuthzTrans trans, Mapper<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper,Question question) {
+ this.ques = question;
+ func = new Function(trans, question);
+ this.mapper = mapper;
+
+ }
+
+/***********************************
+ * NAMESPACE
+ ***********************************/
+ /**
+ * createNS
+ * @throws DAOException
+ * @see org.onap.aaf.authz.service.AuthzService#createNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.String)
+ */
+ @ApiDoc(
+ method = POST,
+ path = "/authz/ns",
+ params = {},
+ expectedCode = 201,
+ errorCodes = { 403,404,406,409 },
+ text = { "Namespace consists of: ",
+ "<ul><li>name - What you want to call this Namespace</li>",
+ "<li>responsible(s) - Person(s) who receive Notifications and approves Requests ",
+ "regarding this Namespace. Companies have Policies as to who may take on ",
+ "this Responsibility. Separate multiple identities with commas</li>",
+ "<li>admin(s) - Person(s) who are allowed to make changes on the namespace, ",
+ "including creating Roles, Permissions and Credentials. Separate multiple ",
+ "identities with commas</li></ul>",
+ "Note: Namespaces are dot-delimited (i.e. com.myCompany.myApp) and must be ",
+ "created with parent credentials (i.e. To create com.myCompany.myApp, you must ",
+ "be an admin of com.myCompany or com"
+ }
+ )
+ @Override
+ public Result<Void> createNS(final AuthzTrans trans, REQUEST from, NsType type) {
+ final Result<Namespace> rnamespace = mapper.ns(trans, from);
+ final Validator v = new Validator();
+ if(v.ns(rnamespace).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ final Namespace namespace = rnamespace.value;
+ final Result<NsDAO.Data> parentNs = ques.deriveNs(trans,namespace.name);
+ if(parentNs.notOK()) {
+ return Result.err(parentNs);
+ }
+
+ if(namespace.name.lastIndexOf('.')<0) { // Root Namespace... Function will check if allowed
+ return func.createNS(trans, namespace, false);
+ }
+
+ Result<FutureDAO.Data> fd = mapper.future(trans, NsDAO.TABLE,from,namespace,true,
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return "Create Namespace [" + namespace.name + ']';
+ }
+ },
+ new MayChange() {
+ private Result<NsDAO.Data> rnd;
+ @Override
+ public Result<?> mayChange() {
+ if(rnd==null) {
+ rnd = ques.mayUser(trans, trans.user(), parentNs.value,Access.write);
+ }
+ return rnd;
+ }
+ });
+ switch(fd.status) {
+ case OK:
+ Result<List<Identity>> rfc = func.createFuture(trans, fd.value, namespace.name, trans.user(),parentNs.value, "C");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "NS [%s] is saved for future processing",namespace.name);
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ return func.createNS(trans, namespace, false);
+ default:
+ return Result.err(fd);
+ }
+ }
+
+ @ApiDoc(
+ method = POST,
+ path = "/authz/ns/:ns/admin/:id",
+ params = { "ns|string|true",
+ "id|string|true"
+ },
+ expectedCode = 201,
+ errorCodes = { 403,404,406,409 },
+ text = { "Add an Identity :id to the list of Admins for the Namespace :ns",
+ "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" }
+ )
+ @Override
+ public Result<Void> addAdminNS(AuthzTrans trans, String ns, String id) {
+ return func.addUserRole(trans, id, ns,Question.ADMIN);
+ }
+
+ @ApiDoc(
+ method = DELETE,
+ path = "/authz/ns/:ns/admin/:id",
+ params = { "ns|string|true",
+ "id|string|true"
+ },
+ expectedCode = 200,
+ errorCodes = { 403,404 },
+ text = { "Remove an Identity :id from the list of Admins for the Namespace :ns",
+ "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" }
+ )
+ @Override
+ public Result<Void> delAdminNS(AuthzTrans trans, String ns, String id) {
+ return func.delAdmin(trans,ns,id);
+ }
+
+ @ApiDoc(
+ method = POST,
+ path = "/authz/ns/:ns/responsible/:id",
+ params = { "ns|string|true",
+ "id|string|true"
+ },
+ expectedCode = 201,
+ errorCodes = { 403,404,406,409 },
+ text = { "Add an Identity :id to the list of Responsibles for the Namespace :ns",
+ "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" }
+ )
+ @Override
+ public Result<Void> addResponsibleNS(AuthzTrans trans, String ns, String id) {
+ return func.addUserRole(trans,id,ns,Question.OWNER);
+ }
+
+ @ApiDoc(
+ method = DELETE,
+ path = "/authz/ns/:ns/responsible/:id",
+ params = { "ns|string|true",
+ "id|string|true"
+ },
+ expectedCode = 200,
+ errorCodes = { 403,404 },
+ text = { "Remove an Identity :id to the list of Responsibles for the Namespace :ns",
+ "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)",
+ "Note: A namespace must have at least 1 responsible party"
+ }
+ )
+ @Override
+ public Result<Void> delResponsibleNS(AuthzTrans trans, String ns, String id) {
+ return func.delOwner(trans,ns,id);
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.service.AuthzService#applyModel(org.onap.aaf.authz.env.AuthzTrans, java.lang.Object)
+ */
+ @ApiDoc(
+ method = POST,
+ path = "/authz/ns/:ns/attrib/:key/:value",
+ params = { "ns|string|true",
+ "key|string|true",
+ "value|string|true"},
+ expectedCode = 201,
+ errorCodes = { 403,404,406,409 },
+ text = {
+ "Create an attribute in the Namespace",
+ "You must be given direct permission for key by AAF"
+ }
+ )
+ @Override
+ public Result<Void> createNsAttrib(AuthzTrans trans, String ns, String key, String value) {
+ TimeTaken tt = trans.start("Create NsAttrib " + ns + ':' + key + ':' + value, Env.SUB);
+ try {
+ // Check inputs
+ final Validator v = new Validator();
+ if(v.ns(ns).err() ||
+ v.key(key).err() ||
+ v.value(value).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ // Check if exists already
+ Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
+ if(rlnsd.notOKorIsEmpty()) {
+ return Result.err(rlnsd);
+ }
+ NsDAO.Data nsd = rlnsd.value.get(0);
+
+ // Check for Existence
+ if(nsd.attrib.get(key)!=null) {
+ return Result.err(Status.ERR_ConflictAlreadyExists, "NS Property %s:%s exists", ns, key);
+ }
+
+ // Check if User may put
+ if(!ques.isGranted(trans, trans.user(), Define.ROOT_NS, Question.ATTRIB,
+ ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) {
+ return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key);
+ }
+
+ // Add Attrib
+ nsd.attrib.put(key, value);
+ ques.nsDAO.dao().attribAdd(trans,ns,key,value);
+ return Result.ok();
+ } finally {
+ tt.done();
+ }
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/ns/attrib/:key",
+ params = { "key|string|true" },
+ expectedCode = 200,
+ errorCodes = { 403,404 },
+ text = {
+ "Read Attributes for Namespace"
+ }
+ )
+ @Override
+ public Result<KEYS> readNsByAttrib(AuthzTrans trans, String key) {
+ // Check inputs
+ final Validator v = new Validator();
+ if(v.nullOrBlank("Key",key).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ // May Read
+ if(!ques.isGranted(trans, trans.user(), Define.ROOT_NS, Question.ATTRIB,
+ ":"+trans.org().getDomain()+".*:"+key, Question.READ)) {
+ return Result.err(Status.ERR_Denied,"%s may not read NS by Attrib '%s'",trans.user(),key);
+ }
+
+ Result<Set<String>> rsd = ques.nsDAO.dao().readNsByAttrib(trans, key);
+ if(rsd.notOK()) {
+ return Result.err(rsd);
+ }
+ return mapper().keys(rsd.value);
+ }
+
+
+ @ApiDoc(
+ method = PUT,
+ path = "/authz/ns/:ns/attrib/:key/:value",
+ params = { "ns|string|true",
+ "key|string|true"},
+ expectedCode = 200,
+ errorCodes = { 403,404 },
+ text = {
+ "Update Value on an existing attribute in the Namespace",
+ "You must be given direct permission for key by AAF"
+ }
+ )
+ @Override
+ public Result<?> updateNsAttrib(AuthzTrans trans, String ns, String key, String value) {
+ TimeTaken tt = trans.start("Update NsAttrib " + ns + ':' + key + ':' + value, Env.SUB);
+ try {
+ // Check inputs
+ final Validator v = new Validator();
+ if(v.ns(ns).err() ||
+ v.key(key).err() ||
+ v.value(value).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ // Check if exists already (NS must exist)
+ Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
+ if(rlnsd.notOKorIsEmpty()) {
+ return Result.err(rlnsd);
+ }
+ NsDAO.Data nsd = rlnsd.value.get(0);
+
+ // Check for Existence
+ if(nsd.attrib.get(key)==null) {
+ return Result.err(Status.ERR_NotFound, "NS Property %s:%s exists", ns, key);
+ }
+
+ // Check if User may put
+ if(!ques.isGranted(trans, trans.user(), Define.ROOT_NS, Question.ATTRIB,
+ ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) {
+ return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key);
+ }
+
+ // Add Attrib
+ nsd.attrib.put(key, value);
+
+ return ques.nsDAO.update(trans,nsd);
+
+ } finally {
+ tt.done();
+ }
+ }
+
+ @ApiDoc(
+ method = DELETE,
+ path = "/authz/ns/:ns/attrib/:key",
+ params = { "ns|string|true",
+ "key|string|true"},
+ expectedCode = 200,
+ errorCodes = { 403,404 },
+ text = {
+ "Delete an attribute in the Namespace",
+ "You must be given direct permission for key by AAF"
+ }
+ )
+ @Override
+ public Result<Void> deleteNsAttrib(AuthzTrans trans, String ns, String key) {
+ TimeTaken tt = trans.start("Delete NsAttrib " + ns + ':' + key, Env.SUB);
+ try {
+ // Check inputs
+ final Validator v = new Validator();
+ if(v.nullOrBlank("NS",ns).err() ||
+ v.nullOrBlank("Key",key).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ // Check if exists already
+ Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns);
+ if(rlnsd.notOKorIsEmpty()) {
+ return Result.err(rlnsd);
+ }
+ NsDAO.Data nsd = rlnsd.value.get(0);
+
+ // Check for Existence
+ if(nsd.attrib.get(key)==null) {
+ return Result.err(Status.ERR_NotFound, "NS Property [%s:%s] does not exist", ns, key);
+ }
+
+ // Check if User may del
+ if(!ques.isGranted(trans, trans.user(), Define.ROOT_NS, "attrib", ":com.att.*:"+key, Access.write.name())) {
+ return Result.err(Status.ERR_Denied, "%s may not delete NS Attrib [%s:%s]", trans.user(),ns, key);
+ }
+
+ // Add Attrib
+ nsd.attrib.remove(key);
+ ques.nsDAO.dao().attribRemove(trans,ns,key);
+ return Result.ok();
+ } finally {
+ tt.done();
+ }
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/nss/:id",
+ params = { "id|string|true" },
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = {
+ "Lists the Admin(s), Responsible Party(s), Role(s), Permission(s)",
+ "Credential(s) and Expiration of Credential(s) in Namespace :id",
+ }
+ )
+ @Override
+ public Result<NSS> getNSbyName(AuthzTrans trans, String ns) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("NS", ns).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, ns);
+ if(rlnd.isOK()) {
+ if(rlnd.isEmpty()) {
+ return Result.err(Status.ERR_NotFound, "No data found for %s",ns);
+ }
+ Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+
+ Namespace namespace = new Namespace(rnd.value);
+ Result<List<String>> rd = func.getOwners(trans, namespace.name, false);
+ if(rd.isOK()) {
+ namespace.owner = rd.value;
+ }
+ rd = func.getAdmins(trans, namespace.name, false);
+ if(rd.isOK()) {
+ namespace.admin = rd.value;
+ }
+
+ NSS nss = mapper.newInstance(API.NSS);
+ return mapper.nss(trans, namespace, nss);
+ } else {
+ return Result.err(rlnd);
+ }
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/nss/admin/:id",
+ params = { "id|string|true" },
+ expectedCode = 200,
+ errorCodes = { 403,404 },
+ text = { "Lists all Namespaces where Identity :id is an Admin",
+ "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)"
+ }
+ )
+ @Override
+ public Result<NSS> getNSbyAdmin(AuthzTrans trans, String user, boolean full) {
+ final Validator v = new Validator();
+ if (v.nullOrBlank("User", user).err()) {
+ return Result.err(Status.ERR_BadData, v.errs());
+ }
+
+ Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".admin", full);
+ if(rn.notOK()) {
+ return Result.err(rn);
+ }
+ if (rn.isEmpty()) {
+ return Result.err(Status.ERR_NotFound, "[%s] is not an admin for any namespaces",user);
+ }
+ NSS nss = mapper.newInstance(API.NSS);
+ // Note: "loadNamespace" already validates view of Namespace
+ return mapper.nss(trans, rn.value, nss);
+
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/nss/either/:id",
+ params = { "id|string|true" },
+ expectedCode = 200,
+ errorCodes = { 403,404 },
+ text = { "Lists all Namespaces where Identity :id is either an Admin or an Owner",
+ "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)"
+ }
+ )
+ @Override
+ public Result<NSS> getNSbyEither(AuthzTrans trans, String user, boolean full) {
+ final Validator v = new Validator();
+ if (v.nullOrBlank("User", user).err()) {
+ return Result.err(Status.ERR_BadData, v.errs());
+ }
+
+ Result<Collection<Namespace>> rn = loadNamepace(trans, user, null, full);
+ if(rn.notOK()) {
+ return Result.err(rn);
+ }
+ if (rn.isEmpty()) {
+ return Result.err(Status.ERR_NotFound, "[%s] is not an admin or owner for any namespaces",user);
+ }
+ NSS nss = mapper.newInstance(API.NSS);
+ // Note: "loadNamespace" already validates view of Namespace
+ return mapper.nss(trans, rn.value, nss);
+ }
+
+ private Result<Collection<Namespace>> loadNamepace(AuthzTrans trans, String user, String endsWith, boolean full) {
+ Result<List<UserRoleDAO.Data>> urd = ques.userRoleDAO.readByUser(trans, user);
+ if(urd.notOKorIsEmpty()) {
+ return Result.err(urd);
+ }
+ Map<String, Namespace> lm = new HashMap<String,Namespace>();
+ Map<String, Namespace> other = full || endsWith==null?null:new TreeMap<String,Namespace>();
+ for(UserRoleDAO.Data urdd : urd.value) {
+ if(full) {
+ if(endsWith==null || urdd.role.endsWith(endsWith)) {
+ RoleDAO.Data rd = RoleDAO.Data.decode(urdd);
+ Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read);
+ if(nsd.isOK()) {
+ Namespace namespace = lm.get(nsd.value.name);
+ if(namespace==null) {
+ namespace = new Namespace(nsd.value);
+ lm.put(namespace.name,namespace);
+ }
+ Result<List<String>> rls = func.getAdmins(trans, namespace.name, false);
+ if(rls.isOK()) {
+ namespace.admin=rls.value;
+ }
+
+ rls = func.getOwners(trans, namespace.name, false);
+ if(rls.isOK()) {
+ namespace.owner=rls.value;
+ }
+ }
+ }
+ } else { // Shortened version. Only Namespace Info available from Role.
+ if(Question.ADMIN.equals(urdd.rname) || Question.OWNER.equals(urdd.rname)) {
+ RoleDAO.Data rd = RoleDAO.Data.decode(urdd);
+ Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read);
+ if(nsd.isOK()) {
+ Namespace namespace = lm.get(nsd.value.name);
+ if(namespace==null) {
+ if(other!=null) {
+ namespace = other.remove(nsd.value.name);
+ }
+ if(namespace==null) {
+ namespace = new Namespace(nsd.value);
+ namespace.admin=new ArrayList<String>();
+ namespace.owner=new ArrayList<String>();
+ }
+ if(endsWith==null || urdd.role.endsWith(endsWith)) {
+ lm.put(namespace.name,namespace);
+ } else {
+ other.put(namespace.name,namespace);
+ }
+ }
+ if(Question.OWNER.equals(urdd.rname)) {
+ namespace.owner.add(urdd.user);
+ } else {
+ namespace.admin.add(urdd.user);
+ }
+ }
+ }
+ }
+ }
+ return Result.ok(lm.values());
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/nss/responsible/:id",
+ params = { "id|string|true" },
+ expectedCode = 200,
+ errorCodes = { 403,404 },
+ text = { "Lists all Namespaces where Identity :id is a Responsible Party",
+ "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)"
+ }
+ )
+ @Override
+ public Result<NSS> getNSbyResponsible(AuthzTrans trans, String user, boolean full) {
+ final Validator v = new Validator();
+ if (v.nullOrBlank("User", user).err()) {
+ return Result.err(Status.ERR_BadData, v.errs());
+ }
+ Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".owner",full);
+ if(rn.notOK()) {
+ return Result.err(rn);
+ }
+ if (rn.isEmpty()) {
+ return Result.err(Status.ERR_NotFound, "[%s] is not an owner for any namespaces",user);
+ }
+ NSS nss = mapper.newInstance(API.NSS);
+ // Note: "loadNamespace" prevalidates
+ return mapper.nss(trans, rn.value, nss);
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/nss/children/:id",
+ params = { "id|string|true" },
+ expectedCode = 200,
+ errorCodes = { 403,404 },
+ text = { "Lists all Child Namespaces of Namespace :id",
+ "Note: This is not a cached read"
+ }
+ )
+ @Override
+ public Result<NSS> getNSsChildren(AuthzTrans trans, String parent) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("NS", parent).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<NsDAO.Data> rnd = ques.deriveNs(trans, parent);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+ rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+ Set<Namespace> lm = new HashSet<Namespace>();
+ Result<List<NsDAO.Data>> rlnd = ques.nsDAO.dao().getChildren(trans, parent);
+ if(rlnd.isOK()) {
+ if(rlnd.isEmpty()) {
+ return Result.err(Status.ERR_NotFound, "No data found for %s",parent);
+ }
+ for(NsDAO.Data ndd : rlnd.value) {
+ Namespace namespace = new Namespace(ndd);
+ Result<List<String>> rls = func.getAdmins(trans, namespace.name, false);
+ if(rls.isOK()) {
+ namespace.admin=rls.value;
+ }
+
+ rls = func.getOwners(trans, namespace.name, false);
+ if(rls.isOK()) {
+ namespace.owner=rls.value;
+ }
+
+ lm.add(namespace);
+ }
+ NSS nss = mapper.newInstance(API.NSS);
+ return mapper.nss(trans,lm, nss);
+ } else {
+ return Result.err(rlnd);
+ }
+ }
+
+
+ @ApiDoc(
+ method = PUT,
+ path = "/authz/ns",
+ params = {},
+ expectedCode = 200,
+ errorCodes = { 403,404,406 },
+ text = { "Replace the Current Description of a Namespace with a new one"
+ }
+ )
+ @Override
+ public Result<Void> updateNsDescription(AuthzTrans trans, REQUEST from) {
+ final Result<Namespace> nsd = mapper.ns(trans, from);
+ final Validator v = new Validator();
+ if(v.ns(nsd).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ if(v.nullOrBlank("description", nsd.value.description).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Namespace namespace = nsd.value;
+ Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, namespace.name);
+
+ if(rlnd.notOKorIsEmpty()) {
+ return Result.err(Status.ERR_NotFound, "Namespace [%s] does not exist",namespace.name);
+ }
+
+ if (ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.write).notOK()) {
+ return Result.err(Status.ERR_Denied, "You do not have approval to change %s",namespace.name);
+ }
+
+ Result<Void> rdr = ques.nsDAO.dao().addDescription(trans, namespace.name, namespace.description);
+ if(rdr.isOK()) {
+ return Result.ok();
+ } else {
+ return Result.err(rdr);
+ }
+ }
+
+ /**
+ * deleteNS
+ * @throws DAOException
+ * @see org.onap.aaf.authz.service.AuthzService#deleteNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.String)
+ */
+ @ApiDoc(
+ method = DELETE,
+ path = "/authz/ns/:ns",
+ params = { "ns|string|true" },
+ expectedCode = 200,
+ errorCodes = { 403,404,424 },
+ text = { "Delete the Namespace :ns. Namespaces cannot normally be deleted when there ",
+ "are still credentials associated with them, but they can be deleted by setting ",
+ "the \"force\" property. To do this: Add 'force=true' as a query parameter",
+ "<p>WARNING: Using force will delete all credentials attached to this namespace. Use with care.</p>"
+ + "if the \"force\" property is set to 'force=move', then Permissions and Roles are not deleted,"
+ + "but are retained, and assigned to the Parent Namespace. 'force=move' is not permitted "
+ + "at or below Application Scope"
+ }
+ )
+ @Override
+ public Result<Void> deleteNS(AuthzTrans trans, String ns) {
+ return func.deleteNS(trans, ns);
+ }
+
+
+/***********************************
+ * PERM
+ ***********************************/
+
+ /*
+ * (non-Javadoc)
+ * @see org.onap.aaf.authz.service.AuthzService#createOrUpdatePerm(org.onap.aaf.authz.env.AuthzTrans, java.lang.Object, boolean, java.lang.String, java.lang.String, java.lang.String, java.util.List, java.util.List)
+ */
+ @ApiDoc(
+ method = POST,
+ path = "/authz/perm",
+ params = {},
+ expectedCode = 201,
+ errorCodes = {403,404,406,409},
+ text = { "Permission consists of:",
+ "<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
+ + "is being protected</li>",
+ "<li>instance - a key, possibly multi-dimensional, that identifies a specific "
+ + " instance of the type</li>",
+ "<li>action - what kind of action is allowed</li></ul>",
+ "Note: instance and action can be an *"
+ }
+ )
+ @Override
+ public Result<Void> createPerm(final AuthzTrans trans,REQUEST rreq) {
+ final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq);
+ final Validator v = new Validator(trans);
+ if(v.perm(newPd).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, newPd.value,false,
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return "Create Permission [" +
+ newPd.value.fullType() + '|' +
+ newPd.value.instance + '|' +
+ newPd.value.action + ']';
+ }
+ },
+ new MayChange() {
+ private Result<NsDAO.Data> nsd;
+ @Override
+ public Result<?> mayChange() {
+ if(nsd==null) {
+ nsd = ques.mayUser(trans, trans.user(), newPd.value, Access.write);
+ }
+ return nsd;
+ }
+ });
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, newPd.value.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+ switch(fd.status) {
+ case OK:
+ Result<List<Identity>> rfc = func.createFuture(trans,fd.value,
+ newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action,
+ trans.user(),
+ nsr.value.get(0),
+ "C");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
+ newPd.value.ns,
+ newPd.value.type,
+ newPd.value.instance,
+ newPd.value.action);
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ return func.createPerm(trans, newPd.value, true);
+ default:
+ return Result.err(fd);
+ }
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/perms/:type",
+ params = {"type|string|true"},
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = { "List All Permissions that match the :type element of the key" }
+ )
+ @Override
+ public Result<PERMS> getPermsByType(AuthzTrans trans, final String permType) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("PermType", permType).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<List<PermDAO.Data>> rlpd = ques.getPermsByType(trans, permType);
+ if(rlpd.notOK()) {
+ return Result.err(rlpd);
+ }
+
+// We don't have instance & action for mayUserView... do we want to loop through all returned here as well as in mapper?
+// Result<NsDAO.Data> r;
+// if((r = ques.mayUserViewPerm(trans, trans.user(), permType)).notOK())return Result.err(r);
+
+ PERMS perms = mapper.newInstance(API.PERMS);
+ if(!rlpd.isEmpty()) {
+ // Note: Mapper will restrict what can be viewed
+ return mapper.perms(trans, rlpd.value, perms, true);
+ }
+ return Result.ok(perms);
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/perms/:type/:instance/:action",
+ params = {"type|string|true",
+ "instance|string|true",
+ "action|string|true"},
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = { "List Permissions that match key; :type, :instance and :action" }
+ )
+ @Override
+ public Result<PERMS> getPermsByName(AuthzTrans trans, String type, String instance, String action) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("PermType", type).err()
+ || v.nullOrBlank("PermInstance", instance).err()
+ || v.nullOrBlank("PermAction", action).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<List<PermDAO.Data>> rlpd = ques.getPermsByName(trans, type, instance, action);
+ if(rlpd.notOK()) {
+ return Result.err(rlpd);
+ }
+
+ PERMS perms = mapper.newInstance(API.PERMS);
+ if(!rlpd.isEmpty()) {
+ // Note: Mapper will restrict what can be viewed
+ return mapper.perms(trans, rlpd.value, perms, true);
+ }
+ return Result.ok(perms);
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/perms/user/:user",
+ params = {"user|string|true"},
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = { "List All Permissions that match user :user",
+ "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>"}
+ )
+ @Override
+ public Result<PERMS> getPermsByUser(AuthzTrans trans, String user) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("User", user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user, trans.forceRequested());
+ if(rlpd.notOK()) {
+ return Result.err(rlpd);
+ }
+
+ PERMS perms = mapper.newInstance(API.PERMS);
+
+ if(rlpd.isEmpty()) {
+ return Result.ok(perms);
+ }
+ // Note: Mapper will restrict what can be viewed
+ // if user is the same as that which is looked up, no filtering is required
+ return mapper.perms(trans, rlpd.value,
+ perms,
+ !user.equals(trans.user()));
+ }
+
+ @ApiDoc(
+ method = POST,
+ path = "/authz/perms/user/:user",
+ params = {"user|string|true"},
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = { "List All Permissions that match user :user",
+ "<p>'user' must be expressed as full identity (ex: id@full.domain.com)</p>",
+ "",
+ "Present Queries as one or more Permissions (see ContentType Links below for format).",
+ "",
+ "If the Caller is Granted this specific Permission, and the Permission is valid",
+ " for the User, it will be included in response Permissions, along with",
+ " all the normal permissions on the 'GET' version of this call. If it is not",
+ " valid, or Caller does not have permission to see, it will be removed from the list",
+ "",
+ " *Note: This design allows you to make one call for all expected permissions",
+ " The permission to be included MUST be:",
+ " <user namespace>.access|:<ns|role|perm>[:key]|<create|read|write>",
+ " examples:",
+ " com.att.myns.access|:ns|write",
+ " com.att.myns.access|:role:myrole|create",
+ " com.att.myns.access|:perm:mytype:myinstance:myaction|read",
+ ""
+ }
+ )
+ @Override
+ public Result<PERMS> getPermsByUser(AuthzTrans trans, PERMS _perms, String user) {
+ PERMS perms = _perms;
+ final Validator v = new Validator();
+ if(v.nullOrBlank("User", user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ //////////////
+ Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user,trans.forceRequested());
+ if(rlpd.notOK()) {
+ return Result.err(rlpd);
+ }
+
+ /*//TODO
+ 1) See if allowed to query
+ 2) See if User is allowed
+ */
+ Result<List<PermDAO.Data>> in = mapper.perms(trans, perms);
+ if(in.isOKhasData()) {
+ List<PermDAO.Data> out = rlpd.value;
+ boolean ok;
+ for(PermDAO.Data pdd : in.value) {
+ ok = false;
+ if("access".equals(pdd.type)) {
+ Access access = Access.valueOf(pdd.action);
+ String[] mdkey = Split.splitTrim(':',pdd.instance);
+ if(mdkey.length>1) {
+ String type = mdkey[1];
+ if("role".equals(type)) {
+ if(mdkey.length>2) {
+ RoleDAO.Data rdd = new RoleDAO.Data();
+ rdd.ns=pdd.ns;
+ rdd.name=mdkey[2];
+ ok = ques.mayUser(trans, trans.user(), rdd, Access.read).isOK() && ques.mayUser(trans, user, rdd , access).isOK();
+ }
+ } else if("perm".equals(type)) {
+ if(mdkey.length>4) { // also need instance/action
+ PermDAO.Data p = new PermDAO.Data();
+ p.ns=pdd.ns;
+ p.type=mdkey[2];
+ p.instance=mdkey[3];
+ p.action=mdkey[4];
+ ok = ques.mayUser(trans, trans.user(), p, Access.read).isOK() && ques.mayUser(trans, user, p , access).isOK();
+ }
+ } else if("ns".equals(type)) {
+ NsDAO.Data ndd = new NsDAO.Data();
+ ndd.name=pdd.ns;
+ ok = ques.mayUser(trans, trans.user(), ndd, Access.read).isOK() && ques.mayUser(trans, user, ndd , access).isOK();
+ }
+ }
+ }
+ if(ok) {
+ out.add(pdd);
+ }
+ }
+ }
+
+ perms = mapper.newInstance(API.PERMS);
+ if(rlpd.isEmpty()) {
+ return Result.ok(perms);
+ }
+ // Note: Mapper will restrict what can be viewed
+ // if user is the same as that which is looked up, no filtering is required
+ return mapper.perms(trans, rlpd.value,
+ perms,
+ !user.equals(trans.user()));
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/perms/role/:role",
+ params = {"role|string|true"},
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = { "List All Permissions that are granted to :role" }
+ )
+ @Override
+ public Result<PERMS> getPermsByRole(AuthzTrans trans,String role) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("Role", role).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques,role);
+ if(rrdd.notOK()) {
+ return Result.err(rrdd);
+ }
+
+ Result<NsDAO.Data> r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read);
+ if(r.notOK()) {
+ return Result.err(r);
+ }
+
+ PERMS perms = mapper.newInstance(API.PERMS);
+
+ Result<List<PermDAO.Data>> rlpd = ques.getPermsByRole(trans, role, trans.forceRequested());
+ if(rlpd.isOKhasData()) {
+ // Note: Mapper will restrict what can be viewed
+ return mapper.perms(trans, rlpd.value, perms, true);
+ }
+ return Result.ok(perms);
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/perms/ns/:ns",
+ params = {"ns|string|true"},
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = { "List All Permissions that are in Namespace :ns" }
+ )
+ @Override
+ public Result<PERMS> getPermsByNS(AuthzTrans trans,String ns) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("NS", ns).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<NsDAO.Data> rnd = ques.deriveNs(trans, ns);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+ rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+ Result<List<PermDAO.Data>> rlpd = ques.permDAO.readNS(trans, ns);
+ if(rlpd.notOK()) {
+ return Result.err(rlpd);
+ }
+
+ PERMS perms = mapper.newInstance(API.PERMS);
+ if(!rlpd.isEmpty()) {
+ // Note: Mapper will restrict what can be viewed
+ return mapper.perms(trans, rlpd.value,perms, true);
+ }
+ return Result.ok(perms);
+ }
+
+ @ApiDoc(
+ method = PUT,
+ path = "/authz/perm/:type/:instance/:action",
+ params = {"type|string|true",
+ "instance|string|true",
+ "action|string|true"},
+ expectedCode = 200,
+ errorCodes = { 404,406, 409 },
+ text = { "Rename the Permission referenced by :type :instance :action, and "
+ + "rename (copy/delete) to the Permission described in PermRequest" }
+ )
+ @Override
+ public Result<Void> renamePerm(final AuthzTrans trans,REQUEST rreq, String origType, String origInstance, String origAction) {
+ final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq);
+ final Validator v = new Validator(trans);
+ if(v.perm(newPd).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ if (ques.mayUser(trans, trans.user(), newPd.value,Access.write).notOK()) {
+ return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]",
+ newPd.value.ns,newPd.value.type,newPd.value.instance,newPd.value.action);
+ }
+
+ Result<NsSplit> nss = ques.deriveNsSplit(trans, origType);
+ Result<List<PermDAO.Data>> origRlpd = ques.permDAO.read(trans, nss.value.ns, nss.value.name, origInstance, origAction);
+
+ if(origRlpd.notOKorIsEmpty()) {
+ return Result.err(Status.ERR_PermissionNotFound,
+ "Permission [%s|%s|%s] does not exist",
+ origType,origInstance,origAction);
+ }
+
+ PermDAO.Data origPd = origRlpd.value.get(0);
+
+ if (!origPd.ns.equals(newPd.value.ns)) {
+ return Result.err(Status.ERR_Denied, "Cannot change namespace with rename command. " +
+ "<new type> must start with [" + origPd.ns + "]");
+ }
+
+ if ( origPd.type.equals(newPd.value.type) &&
+ origPd.action.equals(newPd.value.action) &&
+ origPd.instance.equals(newPd.value.instance) ) {
+ return Result.err(Status.ERR_ConflictAlreadyExists, "New Permission must be different than original permission");
+ }
+
+ Set<String> origRoles = origPd.roles(false);
+ if (!origRoles.isEmpty()) {
+ Set<String> roles = newPd.value.roles(true);
+ for (String role : origPd.roles) {
+ roles.add(role);
+ }
+ }
+
+ newPd.value.description = origPd.description;
+
+ Result<Void> rv = null;
+
+ rv = func.createPerm(trans, newPd.value, false);
+ if (rv.isOK()) {
+ rv = func.deletePerm(trans, origPd, true, false);
+ }
+ return rv;
+ }
+
+ @ApiDoc(
+ method = PUT,
+ path = "/authz/perm",
+ params = {},
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = { "Add Description Data to Perm" }
+ )
+ @Override
+ public Result<Void> updatePermDescription(AuthzTrans trans, REQUEST from) {
+ final Result<PermDAO.Data> pd = mapper.perm(trans, from);
+ final Validator v = new Validator(trans);
+ if(v.perm(pd).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ if(v.nullOrBlank("description", pd.value.description).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ final PermDAO.Data perm = pd.value;
+ if(ques.permDAO.read(trans, perm.ns, perm.type, perm.instance,perm.action).notOKorIsEmpty()) {
+ return Result.err(Status.ERR_NotFound, "Permission [%s.%s|%s|%s] does not exist",
+ perm.ns,perm.type,perm.instance,perm.action);
+ }
+
+ if (ques.mayUser(trans, trans.user(), perm, Access.write).notOK()) {
+ return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]",
+ perm.ns,perm.type,perm.instance,perm.action);
+ }
+
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pd.value.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+
+ Result<Void> rdr = ques.permDAO.addDescription(trans, perm.ns, perm.type, perm.instance,
+ perm.action, perm.description);
+ if(rdr.isOK()) {
+ return Result.ok();
+ } else {
+ return Result.err(rdr);
+ }
+
+ }
+
+ @ApiDoc(
+ method = PUT,
+ path = "/authz/role/perm",
+ params = {},
+ expectedCode = 201,
+ errorCodes = {403,404,406,409},
+ text = { "Set a permission's roles to roles given" }
+ )
+
+ @Override
+ public Result<Void> resetPermRoles(final AuthzTrans trans, REQUEST rreq) {
+ final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq);
+ if(updt.notOKorIsEmpty()) {
+ return Result.err(updt);
+ }
+
+ final Validator v = new Validator(trans);
+ if(v.perm(updt).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write);
+ if (nsd.notOK()) {
+ return Result.err(nsd);
+ }
+
+ // Read full set to get CURRENT values
+ Result<List<PermDAO.Data>> rcurr = ques.permDAO.read(trans,
+ updt.value.ns,
+ updt.value.type,
+ updt.value.instance,
+ updt.value.action);
+
+ if(rcurr.notOKorIsEmpty()) {
+ return Result.err(Status.ERR_PermissionNotFound,
+ "Permission [%s.%s|%s|%s] does not exist",
+ updt.value.ns,updt.value.type,updt.value.instance,updt.value.action);
+ }
+
+ // Create a set of Update Roles, which are in Internal Format
+ Set<String> updtRoles = new HashSet<String>();
+ Result<NsSplit> nss;
+ for(String role : updt.value.roles(false)) {
+ nss = ques.deriveNsSplit(trans, role);
+ if(nss.isOK()) {
+ updtRoles.add(nss.value.ns + '|' + nss.value.name);
+ } else {
+ trans.error().log(nss.errorString());
+ }
+ }
+
+ Result<Void> rv = null;
+
+ for(PermDAO.Data curr : rcurr.value) {
+ Set<String> currRoles = curr.roles(false);
+ // must add roles to this perm, and add this perm to each role
+ // in the update, but not in the current
+ for (String role : updtRoles) {
+ if (!currRoles.contains(role)) {
+ Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role);
+ if(key.isOKhasData()) {
+ Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, key.value);
+ if(rrd.isOKhasData()) {
+ for(RoleDAO.Data r : rrd.value) {
+ rv = func.addPermToRole(trans, r, curr, false);
+ if (rv.notOK() && rv.status!=Result.ERR_ConflictAlreadyExists) {
+ return Result.err(rv);
+ }
+ }
+ } else {
+ return Result.err(rrd);
+ }
+ }
+ }
+ }
+ // similarly, must delete roles from this perm, and delete this perm from each role
+ // in the update, but not in the current
+ for (String role : currRoles) {
+ if (!updtRoles.contains(role)) {
+ Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role);
+ if(key.isOKhasData()) {
+ Result<List<RoleDAO.Data>> rdd = ques.roleDAO.read(trans, key.value);
+ if(rdd.isOKhasData()) {
+ for(RoleDAO.Data r : rdd.value) {
+ rv = func.delPermFromRole(trans, r, curr, true);
+ if (rv.notOK() && rv.status!=Status.ERR_PermissionNotFound) {
+ return Result.err(rv);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return rv==null?Result.ok():rv;
+ }
+
+ @ApiDoc(
+ method = DELETE,
+ path = "/authz/perm",
+ params = {},
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = { "Delete the Permission referenced by PermKey.",
+ "You cannot normally delete a permission which is still granted to roles,",
+ "however the \"force\" property allows you to do just that. To do this: Add",
+ "'force=true' as a query parameter.",
+ "<p>WARNING: Using force will ungrant this permission from all roles. Use with care.</p>" }
+ )
+ @Override
+ public Result<Void> deletePerm(final AuthzTrans trans, REQUEST from) {
+ Result<PermDAO.Data> pd = mapper.perm(trans, from);
+ if(pd.notOK()) {
+ return Result.err(pd);
+ }
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank(pd.value).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ final PermDAO.Data perm = pd.value;
+ if (ques.permDAO.read(trans, perm).notOKorIsEmpty()) {
+ return Result.err(Status.ERR_PermissionNotFound, "Permission [%s.%s|%s|%s] does not exist",
+ perm.ns,perm.type,perm.instance,perm.action );
+ }
+
+ Result<FutureDAO.Data> fd = mapper.future(trans,PermDAO.TABLE,from,perm,false,
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return "Delete Permission [" + perm.fullPerm() + ']';
+ }
+ },
+ new MayChange() {
+ private Result<NsDAO.Data> nsd;
+ @Override
+ public Result<?> mayChange() {
+ if(nsd==null) {
+ nsd = ques.mayUser(trans, trans.user(), perm, Access.write);
+ }
+ return nsd;
+ }
+ });
+
+ switch(fd.status) {
+ case OK:
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, perm.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+
+ Result<List<Identity>> rfc = func.createFuture(trans, fd.value,
+ perm.encode(), trans.user(),nsr.value.get(0),"D");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "Perm Deletion [%s] is saved for future processing",perm.encode());
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ return func.deletePerm(trans,perm,trans.forceRequested(), false);
+ default:
+ return Result.err(fd);
+ }
+ }
+
+ @ApiDoc(
+ method = DELETE,
+ path = "/authz/perm/:name/:type/:action",
+ params = {"type|string|true",
+ "instance|string|true",
+ "action|string|true"},
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = { "Delete the Permission referenced by :type :instance :action",
+ "You cannot normally delete a permission which is still granted to roles,",
+ "however the \"force\" property allows you to do just that. To do this: Add",
+ "'force=true' as a query parameter",
+ "<p>WARNING: Using force will ungrant this permission from all roles. Use with care.</p>"}
+ )
+ @Override
+ public Result<Void> deletePerm(AuthzTrans trans, String type, String instance, String action) {
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank("Type",type)
+ .nullOrBlank("Instance",instance)
+ .nullOrBlank("Action",action)
+ .err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<PermDAO.Data> pd = ques.permFrom(trans, type, instance, action);
+ if(pd.isOK()) {
+ return func.deletePerm(trans, pd.value, trans.forceRequested(), false);
+ } else {
+ return Result.err(pd);
+ }
+ }
+
+/***********************************
+ * ROLE
+ ***********************************/
+ @ApiDoc(
+ method = POST,
+ path = "/authz/role",
+ params = {},
+ expectedCode = 201,
+ errorCodes = {403,404,406,409},
+ text = {
+
+ "Roles are part of Namespaces",
+ "Examples:",
+ "<ul><li> org.osaaf - A Possible root Namespace for maintaining AAF</li>",
+ "Roles do not include implied permissions for an App. Instead, they contain explicit Granted Permissions by any Namespace in AAF (See Permissions)",
+ "Restrictions on Role Names:",
+ "<ul><li>Must start with valid Namespace name, terminated by . (dot/period)</li>",
+ "<li>Allowed Characters are a-zA-Z0-9._-</li>",
+ "<li>role names are Case Sensitive</li></ul>",
+ "The right questions to ask for defining and populating a Role in AAF, therefore, are:",
+ "<ul><li>'What Job Function does this represent?'</li>",
+ "<li>'Does this person perform this Job Function?'</li></ul>" }
+ )
+
+ @Override
+ public Result<Void> createRole(final AuthzTrans trans, REQUEST from) {
+ final Result<RoleDAO.Data> rd = mapper.role(trans, from);
+ final Validator v = new Validator(trans);
+ if(v.role(rd).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ final RoleDAO.Data role = rd.value;
+ if(ques.roleDAO.read(trans, role.ns, role.name).isOKhasData()) {
+ return Result.err(Status.ERR_ConflictAlreadyExists, "Role [" + role.fullName() + "] already exists");
+ }
+
+ Result<FutureDAO.Data> fd = mapper.future(trans,RoleDAO.TABLE,from,role,false,
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return "Create Role [" +
+ rd.value.fullName() +
+ ']';
+ }
+ },
+ new MayChange() {
+ private Result<NsDAO.Data> nsd;
+ @Override
+ public Result<?> mayChange() {
+ if(nsd==null) {
+ nsd = ques.mayUser(trans, trans.user(), role, Access.write);
+ }
+ return nsd;
+ }
+ });
+
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+
+ switch(fd.status) {
+ case OK:
+ Result<List<Identity>> rfc = func.createFuture(trans, fd.value,
+ role.encode(), trans.user(),nsr.value.get(0),"C");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "Role [%s.%s] is saved for future processing",
+ rd.value.ns,
+ rd.value.name);
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ Result<RoleDAO.Data> rdr = ques.roleDAO.create(trans, role);
+ if(rdr.isOK()) {
+ return Result.ok();
+ } else {
+ return Result.err(rdr);
+ }
+ default:
+ return Result.err(fd);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.service.AuthzService#getRolesByName(org.onap.aaf.authz.env.AuthzTrans, java.lang.String)
+ */
+ @ApiDoc(
+ method = GET,
+ path = "/authz/roles/:role",
+ params = {"role|string|true"},
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "List Roles that match :role",
+ "Note: You must have permission to see any given role"
+ }
+ )
+ @Override
+ public Result<ROLES> getRolesByName(AuthzTrans trans, String role) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("Role", role).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ // Determine if User can ask this question
+ Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
+ if(rrdd.isOKhasData()) {
+ Result<NsDAO.Data> r;
+ if((r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read)).notOK()) {
+ return Result.err(r);
+ }
+ } else {
+ return Result.err(rrdd);
+ }
+
+ // Look up data
+ Result<List<RoleDAO.Data>> rlrd = ques.getRolesByName(trans, role);
+ if(rlrd.isOK()) {
+ // Note: Mapper will restrict what can be viewed
+ ROLES roles = mapper.newInstance(API.ROLES);
+ return mapper.roles(trans, rlrd.value, roles, true);
+ } else {
+ return Result.err(rlrd);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.service.AuthzService#getRolesByUser(org.onap.aaf.authz.env.AuthzTrans, java.lang.String)
+ */
+ @ApiDoc(
+ method = GET,
+ path = "/authz/roles/user/:name",
+ params = {"name|string|true"},
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "List all Roles that match user :name",
+ "'user' must be expressed as full identity (ex: id@full.domain.com)",
+ "Note: You must have permission to see any given role"
+ }
+ )
+
+ @Override
+ public Result<ROLES> getRolesByUser(AuthzTrans trans, String user) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("User", user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ ROLES roles = mapper.newInstance(API.ROLES);
+ // Get list of roles per user, then add to Roles as we go
+ Result<List<RoleDAO.Data>> rlrd;
+ Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user);
+ if(rlurd.isOKhasData()) {
+ for(UserRoleDAO.Data urd : rlurd.value ) {
+ rlrd = ques.roleDAO.read(trans, urd.ns,urd.rname);
+ // Note: Mapper will restrict what can be viewed
+ // if user is the same as that which is looked up, no filtering is required
+ if(rlrd.isOKhasData()) {
+ mapper.roles(trans, rlrd.value,roles, !user.equals(trans.user()));
+ }
+ }
+ }
+ return Result.ok(roles);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.onap.aaf.authz.service.AuthzService#getRolesByNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String)
+ */
+ @ApiDoc(
+ method = GET,
+ path = "/authz/roles/ns/:ns",
+ params = {"ns|string|true"},
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "List all Roles for the Namespace :ns",
+ "Note: You must have permission to see any given role"
+ }
+ )
+
+ @Override
+ public Result<ROLES> getRolesByNS(AuthzTrans trans, String ns) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("NS", ns).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ // check if user is allowed to view NS
+ Result<NsDAO.Data> rnsd = ques.deriveNs(trans, ns);
+ if(rnsd.notOK()) {
+ return Result.err(rnsd);
+ }
+ rnsd = ques.mayUser(trans, trans.user(), rnsd.value, Access.read);
+ if(rnsd.notOK()) {
+ return Result.err(rnsd);
+ }
+
+ TimeTaken tt = trans.start("MAP Roles by NS to Roles", Env.SUB);
+ try {
+ ROLES roles = mapper.newInstance(API.ROLES);
+ // Get list of roles per user, then add to Roles as we go
+ Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readNS(trans, ns);
+ if(rlrd.isOK()) {
+ if(!rlrd.isEmpty()) {
+ // Note: Mapper doesn't need to restrict what can be viewed, because we did it already.
+ mapper.roles(trans,rlrd.value,roles,false);
+ }
+ return Result.ok(roles);
+ } else {
+ return Result.err(rlrd);
+ }
+ } finally {
+ tt.done();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.onap.aaf.authz.service.AuthzService#getRolesByNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String)
+ */
+ @ApiDoc(
+ method = GET,
+ path = "/authz/roles/name/:name",
+ params = {"name|string|true"},
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "List all Roles for only the Name of Role (without Namespace)",
+ "Note: You must have permission to see any given role"
+ }
+ )
+ @Override
+ public Result<ROLES> getRolesByNameOnly(AuthzTrans trans, String name) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("Name", name).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ // User Mapper to make sure user is allowed to view NS
+
+ TimeTaken tt = trans.start("MAP Roles by Name to Roles", Env.SUB);
+ try {
+ ROLES roles = mapper.newInstance(API.ROLES);
+ // Get list of roles per user, then add to Roles as we go
+ Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readName(trans, name);
+ if(rlrd.isOK()) {
+ if(!rlrd.isEmpty()) {
+ // Note: Mapper will restrict what can be viewed
+ mapper.roles(trans,rlrd.value,roles,true);
+ }
+ return Result.ok(roles);
+ } else {
+ return Result.err(rlrd);
+ }
+ } finally {
+ tt.done();
+ }
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/roles/perm/:type/:instance/:action",
+ params = {"type|string|true",
+ "instance|string|true",
+ "action|string|true"},
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "Find all Roles containing the given Permission." +
+ "Permission consists of:",
+ "<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
+ + "is being protected</li>",
+ "<li>instance - a key, possibly multi-dimensional, that identifies a specific "
+ + " instance of the type</li>",
+ "<li>action - what kind of action is allowed</li></ul>",
+ "Notes: instance and action can be an *",
+ " You must have permission to see any given role"
+ }
+ )
+
+ @Override
+ public Result<ROLES> getRolesByPerm(AuthzTrans trans, String type, String instance, String action) {
+ final Validator v = new Validator(trans);
+ if(v.permType(type,null)
+ .permInstance(instance)
+ .permAction(action)
+ .err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ TimeTaken tt = trans.start("Map Perm Roles Roles", Env.SUB);
+ try {
+ ROLES roles = mapper.newInstance(API.ROLES);
+ // Get list of roles per user, then add to Roles as we go
+ Result<NsSplit> nsSplit = ques.deriveNsSplit(trans, type);
+ if(nsSplit.isOK()) {
+ PermDAO.Data pdd = new PermDAO.Data(nsSplit.value, instance, action);
+ Result<?> res;
+ if((res=ques.mayUser(trans, trans.user(), pdd, Question.Access.read)).notOK()) {
+ return Result.err(res);
+ }
+
+ Result<List<PermDAO.Data>> pdlr = ques.permDAO.read(trans, pdd);
+ if(pdlr.isOK())for(PermDAO.Data pd : pdlr.value) {
+ Result<List<RoleDAO.Data>> rlrd;
+ for(String r : pd.roles) {
+ Result<String[]> rs = RoleDAO.Data.decodeToArray(trans, ques, r);
+ if(rs.isOK()) {
+ rlrd = ques.roleDAO.read(trans, rs.value[0],rs.value[1]);
+ // Note: Mapper will restrict what can be viewed
+ if(rlrd.isOKhasData()) {
+ mapper.roles(trans,rlrd.value,roles,true);
+ }
+ }
+ }
+ }
+ }
+ return Result.ok(roles);
+ } finally {
+ tt.done();
+ }
+ }
+
+ @ApiDoc(
+ method = PUT,
+ path = "/authz/role",
+ params = {},
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "Add Description Data to a Role" }
+ )
+
+ @Override
+ public Result<Void> updateRoleDescription(AuthzTrans trans, REQUEST from) {
+ final Result<RoleDAO.Data> rd = mapper.role(trans, from);
+ final Validator v = new Validator(trans);
+ if(v.role(rd).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ } {
+ if(v.nullOrBlank("description", rd.value.description).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ }
+ final RoleDAO.Data role = rd.value;
+ if(ques.roleDAO.read(trans, role.ns, role.name).notOKorIsEmpty()) {
+ return Result.err(Status.ERR_NotFound, "Role [" + role.fullName() + "] does not exist");
+ }
+
+ if (ques.mayUser(trans, trans.user(), role, Access.write).notOK()) {
+ return Result.err(Status.ERR_Denied, "You do not have approval to change " + role.fullName());
+ }
+
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+
+ Result<Void> rdr = ques.roleDAO.addDescription(trans, role.ns, role.name, role.description);
+ if(rdr.isOK()) {
+ return Result.ok();
+ } else {
+ return Result.err(rdr);
+ }
+
+ }
+
+ @ApiDoc(
+ method = POST,
+ path = "/authz/role/perm",
+ params = {},
+ expectedCode = 201,
+ errorCodes = {403,404,406,409},
+ text = { "Grant a Permission to a Role",
+ "Permission consists of:",
+ "<ul><li>type - a Namespace qualified identifier specifying what kind of resource "
+ + "is being protected</li>",
+ "<li>instance - a key, possibly multi-dimensional, that identifies a specific "
+ + " instance of the type</li>",
+ "<li>action - what kind of action is allowed</li></ul>",
+ "Note: instance and action can be an *",
+ "Note: Using the \"force\" property will create the Permission, if it doesn't exist AND the requesting " +
+ " ID is allowed to create. It will then grant",
+ " the permission to the role in one step. To do this: add 'force=true' as a query parameter."
+ }
+ )
+
+ @Override
+ public Result<Void> addPermToRole(final AuthzTrans trans, REQUEST rreq) {
+ // Translate Request into Perm and Role Objects
+ final Result<PermDAO.Data> rpd = mapper.permFromRPRequest(trans, rreq);
+ if(rpd.notOKorIsEmpty()) {
+ return Result.err(rpd);
+ }
+ final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq);
+ if(rrd.notOKorIsEmpty()) {
+ return Result.err(rrd);
+ }
+
+ // Validate Role and Perm values
+ final Validator v = new Validator(trans);
+ if(v.perm(rpd.value)
+ .role(rrd.value)
+ .err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.read(trans, rrd.value.ns, rrd.value.name);
+ if(rlrd.notOKorIsEmpty()) {
+ return Result.err(Status.ERR_RoleNotFound, "Role [%s] does not exist", rrd.value.fullName());
+ }
+
+ // Check Status of Data in DB (does it exist)
+ Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, rpd.value.ns,
+ rpd.value.type, rpd.value.instance, rpd.value.action);
+ PermDAO.Data createPerm = null; // if not null, create first
+ if(rlpd.notOKorIsEmpty()) { // Permission doesn't exist
+ if(trans.forceRequested()) {
+ // Remove roles from perm data object so we just create the perm here
+ createPerm = rpd.value;
+ createPerm.roles.clear();
+ } else {
+ return Result.err(Status.ERR_PermissionNotFound,"Permission [%s.%s|%s|%s] does not exist",
+ rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action);
+ }
+ } else {
+ if (rlpd.value.get(0).roles(false).contains(rrd.value.encode())) {
+ return Result.err(Status.ERR_ConflictAlreadyExists,
+ "Permission [%s.%s|%s|%s] already granted to Role [%s.%s]",
+ rpd.value.ns,rpd.value.type,rpd.value.instance,rpd.value.action,
+ rrd.value.ns,rrd.value.name
+ );
+ }
+ }
+
+
+ Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, rpd.value,true, // Allow grants to create Approvals
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return "Grant Permission [" + rpd.value.fullPerm() + ']' +
+ " to Role [" + rrd.value.fullName() + "]";
+ }
+ },
+ new MayChange() {
+ private Result<NsDAO.Data> nsd;
+ @Override
+ public Result<?> mayChange() {
+ if(nsd==null) {
+ nsd = ques.mayUser(trans, trans.user(), rpd.value, Access.write);
+ }
+ return nsd;
+ }
+ });
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rpd.value.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+ switch(fd.status) {
+ case OK:
+ Result<List<Identity>> rfc = func.createFuture(trans,fd.value,
+ rpd.value.fullPerm(),
+ trans.user(),
+ nsr.value.get(0),
+ "G");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
+ rpd.value.ns,
+ rpd.value.type,
+ rpd.value.instance,
+ rpd.value.action);
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ Result<Void> rv = null;
+ if(createPerm!=null) {// has been validated for creating
+ rv = func.createPerm(trans, createPerm, false);
+ }
+ if(rv==null || rv.isOK()) {
+ rv = func.addPermToRole(trans, rrd.value, rpd.value, false);
+ }
+ return rv;
+ default:
+ return Result.err(fd);
+ }
+
+ }
+
+ /**
+ * Create a RoleDAO.Data
+ * @param trans
+ * @param roleFullName
+ * @return
+ */
+ @ApiDoc(
+ method = DELETE,
+ path = "/authz/role/:role/perm",
+ params = {"role|string|true"},
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "Ungrant a permission from Role :role" }
+ )
+
+ @Override
+ public Result<Void> delPermFromRole(final AuthzTrans trans, REQUEST rreq) {
+ final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq);
+ if(updt.notOKorIsEmpty()) {
+ return Result.err(updt);
+ }
+ final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq);
+ if(rrd.notOKorIsEmpty()) {
+ return Result.err(rrd);
+ }
+
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank(updt.value)
+ .nullOrBlank(rrd.value)
+ .err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, updt.value.ns, updt.value.type,
+ updt.value.instance, updt.value.action);
+
+ if(rlpd.notOKorIsEmpty()) {
+ return Result.err(Status.ERR_PermissionNotFound,
+ "Permission [%s.%s|%s|%s] does not exist",
+ updt.value.ns,updt.value.type,updt.value.instance,updt.value.action);
+ }
+
+ Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, updt.value,true, // allow ungrants requests
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return "Ungrant Permission [" + updt.value.fullPerm() + ']' +
+ " from Role [" + rrd.value.fullName() + "]";
+ }
+ },
+ new MayChange() {
+ private Result<NsDAO.Data> nsd;
+ @Override
+ public Result<?> mayChange() {
+ if(nsd==null) {
+ nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write);
+ }
+ return nsd;
+ }
+ });
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, updt.value.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+ switch(fd.status) {
+ case OK:
+ Result<List<Identity>> rfc = func.createFuture(trans,fd.value,
+ updt.value.fullPerm(),
+ trans.user(),
+ nsr.value.get(0),
+ "UG"
+ );
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing",
+ updt.value.ns,
+ updt.value.type,
+ updt.value.instance,
+ updt.value.action);
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ return func.delPermFromRole(trans, rrd.value, updt.value, false);
+ default:
+ return Result.err(fd);
+ }
+ }
+
+ @ApiDoc(
+ method = DELETE,
+ path = "/authz/role/:role",
+ params = {"role|string|true"},
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "Delete the Role named :role"}
+ )
+
+ @Override
+ public Result<Void> deleteRole(AuthzTrans trans, String role) {
+ Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
+ if(rrdd.isOKhasData()) {
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank(rrdd.value).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ return func.deleteRole(trans, rrdd.value, false, false);
+ } else {
+ return Result.err(rrdd);
+ }
+ }
+
+ @ApiDoc(
+ method = DELETE,
+ path = "/authz/role",
+ params = {},
+ expectedCode = 200,
+ errorCodes = { 404,406 },
+ text = { "Delete the Role referenced by RoleKey",
+ "You cannot normally delete a role which still has permissions granted or users assigned to it,",
+ "however the \"force\" property allows you to do just that. To do this: Add 'force=true'",
+ "as a query parameter.",
+ "<p>WARNING: Using force will remove all users and permission from this role. Use with care.</p>"}
+ )
+
+ @Override
+ public Result<Void> deleteRole(final AuthzTrans trans, REQUEST from) {
+ final Result<RoleDAO.Data> rd = mapper.role(trans, from);
+ final Validator v = new Validator(trans);
+ if(rd==null) {
+ return Result.err(Status.ERR_BadData,"Request does not contain Role");
+ }
+ if(v.nullOrBlank(rd.value).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ final RoleDAO.Data role = rd.value;
+ if(ques.roleDAO.read(trans, role).notOKorIsEmpty() && !trans.forceRequested()) {
+ return Result.err(Status.ERR_RoleNotFound, "Role [" + role.fullName() + "] does not exist");
+ }
+
+ Result<FutureDAO.Data> fd = mapper.future(trans,RoleDAO.TABLE,from,role,false,
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return "Delete Role [" + role.fullName() + ']'
+ + " and all attached user roles";
+ }
+ },
+ new MayChange() {
+ private Result<NsDAO.Data> nsd;
+ @Override
+ public Result<?> mayChange() {
+ if(nsd==null) {
+ nsd = ques.mayUser(trans, trans.user(), role, Access.write);
+ }
+ return nsd;
+ }
+ });
+
+ switch(fd.status) {
+ case OK:
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+
+ Result<List<Identity>> rfc = func.createFuture(trans, fd.value,
+ role.encode(), trans.user(),nsr.value.get(0),"D");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "Role Deletion [%s.%s] is saved for future processing",
+ rd.value.ns,
+ rd.value.name);
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ return func.deleteRole(trans,role,trans.forceRequested(), true /*preapproved*/);
+ default:
+ return Result.err(fd);
+ }
+
+ }
+
+/***********************************
+ * CRED
+ ***********************************/
+ private class MayCreateCred implements MayChange {
+ private Result<NsDAO.Data> nsd;
+ private AuthzTrans trans;
+ private CredDAO.Data cred;
+ private Executor exec;
+
+ public MayCreateCred(AuthzTrans trans, CredDAO.Data cred, Executor exec) {
+ this.trans = trans;
+ this.cred = cred;
+ this.exec = exec;
+ }
+
+ @Override
+ public Result<?> mayChange() {
+ if(nsd==null) {
+ nsd = ques.validNSOfDomain(trans, cred.id);
+ }
+ // is Ns of CredID valid?
+ if(nsd.isOK()) {
+ try {
+ // Check Org Policy
+ if(trans.org().validate(trans,Policy.CREATE_MECHID, exec, cred.id)==null) {
+ return Result.ok();
+ } else {
+ Result<?> rmc = ques.mayUser(trans, trans.user(), nsd.value, Access.write);
+ if(rmc.isOKhasData()) {
+ return rmc;
+ }
+ }
+ } catch (Exception e) {
+ trans.warn().log(e);
+ }
+ } else {
+ trans.warn().log(nsd.errorString());
+ }
+ return Result.err(Status.ERR_Denied,"%s is not allowed to create %s in %s",trans.user(),cred.id,cred.ns);
+ }
+ }
+
+ private class MayChangeCred implements MayChange {
+
+ private Result<NsDAO.Data> nsd;
+ private AuthzTrans trans;
+ private CredDAO.Data cred;
+ public MayChangeCred(AuthzTrans trans, CredDAO.Data cred) {
+ this.trans = trans;
+ this.cred = cred;
+ }
+
+ @Override
+ public Result<?> mayChange() {
+ // User can change himself (but not create)
+ if(trans.user().equals(cred.id)) {
+ return Result.ok();
+ }
+ if(nsd==null) {
+ nsd = ques.validNSOfDomain(trans, cred.id);
+ }
+ // Get the Namespace
+ if(nsd.isOK()) {
+ if(ques.mayUser(trans, trans.user(), nsd.value,Access.write).isOK()) {
+ return Result.ok();
+ }
+ String user[] = Split.split('.',trans.user());
+ if(user.length>2) {
+ String company = user[user.length-1] + '.' + user[user.length-2];
+ if(ques.isGranted(trans, trans.user(), Define.ROOT_NS,"password",company,"reset")) {
+ return Result.ok();
+ }
+ }
+ }
+ return Result.err(Status.ERR_Denied,"%s is not allowed to change %s in %s",trans.user(),cred.id,cred.ns);
+ }
+
+ }
+
+ private final long DAY_IN_MILLIS = 24*3600*1000;
+
+ @ApiDoc(
+ method = POST,
+ path = "/authn/cred",
+ params = {},
+ expectedCode = 201,
+ errorCodes = {403,404,406,409},
+ text = { "A credential consists of:",
+ "<ul><li>id - the ID to create within AAF. The domain is in reverse",
+ "order of Namespace (i.e. Users of Namespace com.att.myapp would be",
+ "AB1234@myapp.att.com</li>",
+ "<li>password - Company Policy Compliant Password</li></ul>",
+ "Note: AAF does support multiple credentials with the same ID.",
+ "Check with your organization if you have this implemented."
+ }
+ )
+ @Override
+ public Result<Void> createUserCred(final AuthzTrans trans, REQUEST from) {
+ final String cmdDescription = ("Create User Credential");
+ TimeTaken tt = trans.start(cmdDescription, Env.SUB);
+
+ try {
+ Result<CredDAO.Data> rcred = mapper.cred(trans, from, true);
+ if(rcred.isOKhasData()) {
+ rcred = ques.userCredSetup(trans, rcred.value);
+
+ final Validator v = new Validator();
+
+ if(v.cred(trans.org(),rcred,true).err()) { // Note: Creates have stricter Validations
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+
+ // 2016-4 JG, New Behavior - If MechID is not registered with Org, deny creation
+ Identity mechID = null;
+ Organization org = trans.org();
+ try {
+ mechID = org.getIdentity(trans, rcred.value.id);
+ } catch (Exception e1) {
+ trans.error().log(e1,rcred.value.id,"cannot be validated at this time");
+ }
+ if(mechID==null || !mechID.isFound()) {
+ return Result.err(Status.ERR_Policy,"MechIDs must be registered with %s before provisioning in AAF",org.getName());
+ }
+
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(Status.ERR_NsNotFound,"Cannot provision %s on non-existent Namespace %s",mechID.id(),rcred.value.ns);
+ }
+
+ boolean firstID = false;
+ MayChange mc;
+
+ CassExecutor exec = new CassExecutor(trans, func);
+ Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id);
+ if (rlcd.isOKhasData()) {
+ if (!org.canHaveMultipleCreds(rcred.value.id)) {
+ return Result.err(Status.ERR_ConflictAlreadyExists, "Credential exists");
+ }
+ for (CredDAO.Data curr : rlcd.value) {
+ if (Chrono.dateOnlyStamp(curr.expires).equals(Chrono.dateOnlyStamp(rcred.value.expires)) && curr.type==rcred.value.type) {
+ return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists, use 'reset'");
+ }
+ }
+ } else {
+ try {
+ // 2016-04-12 JG If Caller is the Sponsor and is also an Owner of NS, allow without special Perm
+ String theMechID = rcred.value.id;
+ Boolean otherMechIDs = false;
+ // find out if this is the only mechID. other MechIDs mean special handling (not automated)
+ for(CredDAO.Data cd : ques.credDAO.readNS(trans,nsr.value.get(0).name).value) {
+ if(!cd.id.equals(theMechID)) {
+ otherMechIDs = true;
+ break;
+ }
+ }
+ String reason;
+ // We can say "ID does not exist" here
+ if((reason=org.validate(trans, Policy.CREATE_MECHID, exec, theMechID,trans.user(),otherMechIDs.toString()))!=null) {
+ return Result.err(Status.ERR_Denied, reason);
+ }
+ firstID=true;
+ } catch (Exception e) {
+ return Result.err(e);
+ }
+ }
+
+ mc = new MayCreateCred(trans, rcred.value, exec);
+
+ final CredDAO.Data cdd = rcred.value;
+ Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false, // may want to enable in future.
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return cmdDescription + " [" +
+ cdd.id + '|'
+ + cdd.type + '|'
+ + cdd.expires + ']';
+ }
+ },
+ mc);
+
+ switch(fd.status) {
+ case OK:
+ Result<List<Identity>> rfc = func.createFuture(trans, fd.value,
+ rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires,
+ trans.user(), nsr.value.get(0), "C");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s] is saved for future processing",
+ rcred.value.id,
+ Integer.toString(rcred.value.type),
+ rcred.value.expires.toString());
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ try {
+ if(firstID) {
+ // && !nsr.value.get(0).isAdmin(trans.getUserPrincipal().getName())) {
+ Result<List<String>> admins = func.getAdmins(trans, nsr.value.get(0).name, false);
+ // OK, it's a first ID, and not by NS Admin, so let's set TempPassword length
+ // Note, we only do this on First time, because of possibility of
+ // prematurely expiring a production id
+ if(admins.isOKhasData() && !admins.value.contains(trans.user())) {
+ rcred.value.expires = org.expiration(null, Expiration.TempPassword).getTime();
+ }
+ }
+ } catch (Exception e) {
+ trans.error().log(e, "While setting expiration to TempPassword");
+ }
+ Result<?>udr = ques.credDAO.create(trans, rcred.value);
+ if(udr.isOK()) {
+ return Result.ok();
+ }
+ return Result.err(udr);
+ default:
+ return Result.err(fd);
+ }
+
+ } else {
+ return Result.err(rcred);
+ }
+ } finally {
+ tt.done();
+ }
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authn/creds/ns/:ns",
+ params = {"ns|string|true"},
+ expectedCode = 200,
+ errorCodes = {403,404,406},
+ text = { "Return all IDs in Namespace :ns"
+ }
+ )
+ @Override
+ public Result<USERS> getCredsByNS(AuthzTrans trans, String ns) {
+ final Validator v = new Validator();
+ if(v.ns(ns).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ // check if user is allowed to view NS
+ Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+ rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+ TimeTaken tt = trans.start("MAP Creds by NS to Creds", Env.SUB);
+ try {
+ USERS users = mapper.newInstance(API.USERS);
+ Result<List<CredDAO.Data>> rlcd = ques.credDAO.readNS(trans, ns);
+
+ if(rlcd.isOK()) {
+ if(!rlcd.isEmpty()) {
+ return mapper.cred(rlcd.value, users);
+ }
+ return Result.ok(users);
+ } else {
+ return Result.err(rlcd);
+ }
+ } finally {
+ tt.done();
+ }
+
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authn/creds/id/:ns",
+ params = {"id|string|true"},
+ expectedCode = 200,
+ errorCodes = {403,404,406},
+ text = { "Return all IDs in for ID"
+ ,"(because IDs are multiple, due to multiple Expiration Dates)"
+ }
+ )
+ @Override
+ public Result<USERS> getCredsByID(AuthzTrans trans, String id) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("ID",id).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ String ns = Question.domain2ns(id);
+ // check if user is allowed to view NS
+ Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+ rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+ TimeTaken tt = trans.start("MAP Creds by ID to Creds", Env.SUB);
+ try {
+ USERS users = mapper.newInstance(API.USERS);
+ Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, id);
+
+ if(rlcd.isOK()) {
+ if(!rlcd.isEmpty()) {
+ return mapper.cred(rlcd.value, users);
+ }
+ return Result.ok(users);
+ } else {
+ return Result.err(rlcd);
+ }
+ } finally {
+ tt.done();
+ }
+
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authn/certs/id/:id",
+ params = {"id|string|true"},
+ expectedCode = 200,
+ errorCodes = {403,404,406},
+ text = { "Return Cert Info for ID"
+ }
+ )
+ @Override
+ public Result<CERTS> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id) {
+ TimeTaken tt = trans.start("Get Cert Info by ID", Env.SUB);
+ try {
+ CERTS certs = mapper.newInstance(API.CERTS);
+ Result<List<CertDAO.Data>> rlcd = ques.certDAO.readID(trans, id);
+
+ if(rlcd.isOK()) {
+ if(!rlcd.isEmpty()) {
+ return mapper.cert(rlcd.value, certs);
+ }
+ return Result.ok(certs);
+ } else {
+ return Result.err(rlcd);
+ }
+ } finally {
+ tt.done();
+ }
+
+ }
+
+ @ApiDoc(
+ method = PUT,
+ path = "/authn/cred",
+ params = {},
+ expectedCode = 200,
+ errorCodes = {300,403,404,406},
+ text = { "Reset a Credential Password. If multiple credentials exist for this",
+ "ID, you will need to specify which entry you are resetting in the",
+ "CredRequest object"
+ }
+ )
+ @Override
+ public Result<Void> changeUserCred(final AuthzTrans trans, REQUEST from) {
+ final String cmdDescription = "Update User Credential";
+ TimeTaken tt = trans.start(cmdDescription, Env.SUB);
+ try {
+ Result<CredDAO.Data> rcred = mapper.cred(trans, from, true);
+ if(rcred.isOKhasData()) {
+ rcred = ques.userCredSetup(trans, rcred.value);
+
+ final Validator v = new Validator();
+
+ if(v.cred(trans.org(),rcred,false).err()) {// Note: Creates have stricter Validations
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id);
+ if(rlcd.notOKorIsEmpty()) {
+ return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
+ }
+
+ MayChange mc = new MayChangeCred(trans, rcred.value);
+ Result<?> rmc = mc.mayChange();
+ if (rmc.notOK()) {
+ return Result.err(rmc);
+ }
+
+ Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value);
+ if(ri.notOK()) {
+ return Result.err(ri);
+ }
+ int entry = ri.value;
+
+
+ final CredDAO.Data cred = rcred.value;
+
+ Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from, rcred.value,false,
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return cmdDescription + " [" +
+ cred.id + '|'
+ + cred.type + '|'
+ + cred.expires + ']';
+ }
+ },
+ mc);
+
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+
+ switch(fd.status) {
+ case OK:
+ Result<List<Identity>> rfc = func.createFuture(trans, fd.value,
+ rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires,
+ trans.user(), nsr.value.get(0), "U");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s]",
+ rcred.value.id,
+ Integer.toString(rcred.value.type),
+ rcred.value.expires.toString());
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ Result<?>udr = null;
+ // If we are Resetting Password on behalf of someone else (am not the Admin)
+ // use TempPassword Expiration time.
+ Expiration exp;
+ if(ques.isAdmin(trans, trans.user(), nsr.value.get(0).name)) {
+ exp = Expiration.Password;
+ } else {
+ exp = Expiration.TempPassword;
+ }
+
+ Organization org = trans.org();
+ // If user resets password in same day, we will have a primary key conflict, so subtract 1 day
+ if (rlcd.value.get(entry).expires.equals(rcred.value.expires)
+ && rlcd.value.get(entry).type==rcred.value.type) {
+ GregorianCalendar gc = org.expiration(null, exp,rcred.value.id);
+ gc = Chrono.firstMomentOfDay(gc);
+ gc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay());
+ rcred.value.expires = new Date(gc.getTimeInMillis() - DAY_IN_MILLIS);
+ } else {
+ rcred.value.expires = org.expiration(null,exp).getTime();
+ }
+
+ udr = ques.credDAO.create(trans, rcred.value);
+ if(udr.isOK()) {
+ udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false);
+ }
+ if (udr.isOK()) {
+ return Result.ok();
+ }
+
+ return Result.err(udr);
+ default:
+ return Result.err(fd);
+ }
+ } else {
+ return Result.err(rcred);
+ }
+ } finally {
+ tt.done();
+ }
+ }
+
+ /*
+ * Codify the way to get Either Choice Needed or actual Integer from Credit Request
+ */
+ private Result<Integer> selectEntryIfMultiple(final CredRequest cr, List<CredDAO.Data> lcd) {
+ int entry = 0;
+ if (lcd.size() > 1) {
+ String inputOption = cr.getEntry();
+ if (inputOption == null) {
+ String message = selectCredFromList(lcd, false);
+ String[] variables = buildVariables(lcd);
+ return Result.err(Status.ERR_ChoiceNeeded, message, variables);
+ } else {
+ entry = Integer.parseInt(inputOption) - 1;
+ }
+ if (entry < 0 || entry >= lcd.size()) {
+ return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
+ }
+ }
+ return Result.ok(entry);
+ }
+
+ @ApiDoc(
+ method = PUT,
+ path = "/authn/cred/:days",
+ params = {"days|string|true"},
+ expectedCode = 200,
+ errorCodes = {300,403,404,406},
+ text = { "Extend a Credential Expiration Date. The intention of this API is",
+ "to avoid an outage in PROD due to a Credential expiring before it",
+ "can be configured correctly. Measures are being put in place ",
+ "so that this is not abused."
+ }
+ )
+ @Override
+ public Result<Void> extendUserCred(final AuthzTrans trans, REQUEST from, String days) {
+ TimeTaken tt = trans.start("Extend User Credential", Env.SUB);
+ try {
+ Result<CredDAO.Data> cred = mapper.cred(trans, from, false);
+ Organization org = trans.org();
+ final Validator v = new Validator();
+ if(v.notOK(cred).err() ||
+ v.nullOrBlank(cred.value.id, "Invalid ID").err() ||
+ v.user(org,cred.value.id).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ try {
+ String reason;
+ if ((reason=org.validate(trans, Policy.MAY_EXTEND_CRED_EXPIRES, new CassExecutor(trans,func)))!=null) {
+ return Result.err(Status.ERR_Policy,reason);
+ }
+ } catch (Exception e) {
+ String msg;
+ trans.error().log(e, msg="Could not contact Organization for User Validation");
+ return Result.err(Status.ERR_Denied, msg);
+ }
+
+ // Get the list of Cred Entries
+ Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id);
+ if(rlcd.notOKorIsEmpty()) {
+ return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
+ }
+
+ //Need to do the "Pick Entry" mechanism
+ Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value);
+ if(ri.notOK()) {
+ return Result.err(ri);
+ }
+
+ CredDAO.Data found = rlcd.value.get(ri.value);
+ CredDAO.Data cd = cred.value;
+ // Copy over the cred
+ cd.cred = found.cred;
+ cd.type = found.type;
+ cd.expires = org.expiration(null, Expiration.ExtendPassword,days).getTime();
+
+ cred = ques.credDAO.create(trans, cd);
+ if(cred.isOK()) {
+ return Result.ok();
+ }
+ return Result.err(cred);
+ } finally {
+ tt.done();
+ }
+ }
+
+ private String[] buildVariables(List<CredDAO.Data> value) {
+ // ensure credentials are sorted so we can fully automate Cred regression test
+ Collections.sort(value, new Comparator<CredDAO.Data>() {
+ @Override
+ public int compare(CredDAO.Data cred1, CredDAO.Data cred2) {
+ return cred1.expires.compareTo(cred2.expires);
+ }
+ });
+ String [] vars = new String[value.size()+1];
+ vars[0]="Choice";
+ for (int i = 0; i < value.size(); i++) {
+ vars[i+1] = value.get(i).id + " " + value.get(i).type
+ + " |" + value.get(i).expires;
+ }
+ return vars;
+ }
+
+ private String selectCredFromList(List<CredDAO.Data> value, boolean isDelete) {
+ StringBuilder errMessage = new StringBuilder();
+ String userPrompt = isDelete?"Select which cred to delete (set force=true to delete all):":"Select which cred to update:";
+ int numSpaces = value.get(0).id.length() - "Id".length();
+
+ errMessage.append(userPrompt + '\n');
+ errMessage.append(" Id");
+ for (int i = 0; i < numSpaces; i++) {
+ errMessage.append(' ');
+ }
+ errMessage.append(" Type Expires" + '\n');
+ for(int i=0;i<value.size();++i) {
+ errMessage.append(" %s\n");
+ }
+ errMessage.append("Run same command again with chosen entry as last parameter");
+
+ return errMessage.toString();
+
+ }
+
+ @ApiDoc(
+ method = DELETE,
+ path = "/authn/cred",
+ params = {},
+ expectedCode = 200,
+ errorCodes = {300,403,404,406},
+ text = { "Delete a Credential. If multiple credentials exist for this",
+ "ID, you will need to specify which entry you are deleting in the",
+ "CredRequest object."
+ }
+ )
+ @Override
+ public Result<Void> deleteUserCred(AuthzTrans trans, REQUEST from) {
+ final Result<CredDAO.Data> cred = mapper.cred(trans, from, false);
+ final Validator v = new Validator();
+ if(v.nullOrBlank("cred", cred.value.id).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id);
+ if(rlcd.notOKorIsEmpty()) {
+ // Empty Creds should have no user_roles.
+ Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id);
+ if(rlurd.isOK()) {
+ for(UserRoleDAO.Data data : rlurd.value) {
+ ques.userRoleDAO.delete(trans, data, false);
+ }
+ }
+ return Result.err(Status.ERR_UserNotFound, "Credential does not exist");
+ }
+ boolean isLastCred = rlcd.value.size()==1;
+
+ MayChange mc = new MayChangeCred(trans,cred.value);
+ Result<?> rmc = mc.mayChange();
+ if (rmc.notOK()) {
+ return Result.err(rmc);
+ }
+
+ int entry = 0;
+ if(!trans.forceRequested()) {
+ if (rlcd.value.size() > 1) {
+ CredRequest cr = (CredRequest)from;
+ String inputOption = cr.getEntry();
+ if (inputOption == null) {
+ String message = selectCredFromList(rlcd.value, true);
+ String[] variables = buildVariables(rlcd.value);
+ return Result.err(Status.ERR_ChoiceNeeded, message, variables);
+ } else {
+ try {
+ entry = Integer.parseInt(inputOption) - 1;
+ } catch(NumberFormatException e) {
+ return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
+ }
+ }
+ isLastCred = (entry==-1)?true:false;
+ } else {
+ isLastCred = true;
+ }
+ if (entry < -1 || entry >= rlcd.value.size()) {
+ return Result.err(Status.ERR_BadData, "User chose invalid credential selection");
+ }
+ }
+
+ Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from,cred.value,false,
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return "Delete Credential [" +
+ cred.value.id +
+ ']';
+ }
+ },
+ mc);
+
+ Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, cred.value.ns);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+
+ switch(fd.status) {
+ case OK:
+ Result<List<Identity>> rfc = func.createFuture(trans, fd.value, cred.value.id,
+ trans.user(), nsr.value.get(0),"D");
+
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "Credential Delete [%s] is saved for future processing",cred.value.id);
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ Result<?>udr = null;
+ if (!trans.forceRequested()) {
+ if(entry<0 || entry >= rlcd.value.size()) {
+ return Result.err(Status.ERR_BadData,"Invalid Choice [" + entry + "] chosen for Delete [%s] is saved for future processing",cred.value.id);
+ }
+ udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false);
+ } else {
+ for (CredDAO.Data curr : rlcd.value) {
+ udr = ques.credDAO.delete(trans, curr, false);
+ if (udr.notOK()) {
+ return Result.err(udr);
+ }
+ }
+ }
+ if(isLastCred) {
+ Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id);
+ if(rlurd.isOK()) {
+ for(UserRoleDAO.Data data : rlurd.value) {
+ ques.userRoleDAO.delete(trans, data, false);
+ }
+ }
+ }
+ if (udr.isOK()) {
+ return Result.ok();
+ }
+ return Result.err(udr);
+ default:
+ return Result.err(fd);
+ }
+
+ }
+
+
+ @Override
+ public Result<Date> doesCredentialMatch(AuthzTrans trans, REQUEST credReq) {
+ TimeTaken tt = trans.start("Does Credential Match", Env.SUB);
+ try {
+ // Note: Mapper assigns RAW type
+ Result<CredDAO.Data> data = mapper.cred(trans, credReq,false);
+ if(data.notOKorIsEmpty()) {
+ return Result.err(data);
+ }
+ CredDAO.Data cred = data.value; // of the Mapped Cred
+ return ques.doesUserCredMatch(trans, cred.id, cred.cred.array());
+
+ } catch (DAOException e) {
+ trans.error().log(e,"Error looking up cred");
+ return Result.err(Status.ERR_Denied,"Credential does not match");
+ } finally {
+ tt.done();
+ }
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authn/basicAuth",
+ params = {},
+ expectedCode = 200,
+ errorCodes = { 403 },
+ text = { "Validate a Password using BasicAuth Base64 encoded Header. This HTTP/S call is intended as a fast"
+ + " User/Password lookup for Security Frameworks, and responds 200 if it passes BasicAuth "
+ + "security, and 403 if it does not." }
+ )
+ private void basicAuth() {
+ // This is a place holder for Documentation. The real BasicAuth API does not call Service.
+ }
+
+ @ApiDoc(
+ method = POST,
+ path = "/authn/validate",
+ params = {},
+ expectedCode = 200,
+ errorCodes = { 403 },
+ text = { "Validate a Credential given a Credential Structure. This is a more comprehensive validation, can "
+ + "do more than BasicAuth as Credential types exp" }
+ )
+ @Override
+ public Result<Date> validateBasicAuth(AuthzTrans trans, String basicAuth) {
+ //TODO how to make sure people don't use this in browsers? Do we care?
+ TimeTaken tt = trans.start("Validate Basic Auth", Env.SUB);
+ try {
+ BasicPrincipal bp = new BasicPrincipal(basicAuth,trans.org().getRealm());
+ Result<Date> rq = ques.doesUserCredMatch(trans, bp.getName(), bp.getCred());
+ // Note: Only want to log problem, don't want to send back to end user
+ if(rq.isOK()) {
+ return rq;
+ } else {
+ trans.audit().log(rq.errorString());
+ }
+ } catch (Exception e) {
+ trans.warn().log(e);
+ } finally {
+ tt.done();
+ }
+ return Result.err(Status.ERR_Denied,"Bad Basic Auth");
+ }
+
+/***********************************
+ * USER-ROLE
+ ***********************************/
+ @ApiDoc(
+ method = POST,
+ path = "/authz/userRole",
+ params = {},
+ expectedCode = 201,
+ errorCodes = {403,404,406,409},
+ text = { "Create a UserRole relationship (add User to Role)",
+ "A UserRole is an object Representation of membership of a Role for limited time.",
+ "If a shorter amount of time for Role ownership is required, use the 'End' field.",
+ "** Note: Owners of Namespaces will be required to revalidate users in these roles ",
+ "before Expirations expire. Namespace owners will be notified by email."
+ }
+ )
+ @Override
+ public Result<Void> createUserRole(final AuthzTrans trans, REQUEST from) {
+ TimeTaken tt = trans.start("Create UserRole", Env.SUB);
+ try {
+ Result<UserRoleDAO.Data> urr = mapper.userRole(trans, from);
+ if(urr.notOKorIsEmpty()) {
+ return Result.err(urr);
+ }
+ final UserRoleDAO.Data userRole = urr.value;
+
+ final Validator v = new Validator();
+ if(v.user_role(userRole).err() ||
+ v.user(trans.org(), userRole.user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+
+
+ // Check if user can change first
+ Result<FutureDAO.Data> fd = mapper.future(trans,UserRoleDAO.TABLE,from,urr.value,true, // may request Approvals
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ return "Add User [" + userRole.user + "] to Role [" +
+ userRole.role +
+ ']';
+ }
+ },
+ new MayChange() {
+ private Result<NsDAO.Data> nsd;
+ @Override
+ public Result<?> mayChange() {
+ if(nsd==null) {
+ RoleDAO.Data r = RoleDAO.Data.decode(userRole);
+ nsd = ques.mayUser(trans, trans.user(), r, Access.write);
+ }
+ return nsd;
+ }
+ });
+ Result<NsDAO.Data> nsr = ques.deriveNs(trans, userRole.role);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+
+ switch(fd.status) {
+ case OK:
+ Result<List<Identity>> rfc = func.createFuture(trans, fd.value, userRole.user+'|'+userRole.ns + '.' + userRole.rname,
+ userRole.user, nsr.value, "C");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "UserRole [%s - %s.%s] is saved for future processing",
+ userRole.user,
+ userRole.ns,
+ userRole.rname);
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ return func.addUserRole(trans, userRole);
+ default:
+ return Result.err(fd);
+ }
+ } finally {
+ tt.done();
+ }
+ }
+
+ /**
+ * getUserRolesByRole
+ */
+ @ApiDoc(
+ method = GET,
+ path = "/authz/userRoles/role/:role",
+ params = {"role|string|true"},
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "List all Users that are attached to Role specified in :role",
+ }
+ )
+ @Override
+ public Result<USERROLES> getUserRolesByRole(AuthzTrans trans, String role) {
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank("Role",role).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<RoleDAO.Data> rrdd;
+ rrdd = RoleDAO.Data.decode(trans,ques,role);
+ if(rrdd.notOK()) {
+ return Result.err(rrdd);
+ }
+ // May Requester see result?
+ Result<NsDAO.Data> ns = ques.mayUser(trans,trans.user(), rrdd.value,Access.read);
+ if (ns.notOK()) {
+ return Result.err(ns);
+ }
+
+ // boolean filter = true;
+ // if (ns.value.isAdmin(trans.user()) || ns.value.isResponsible(trans.user()))
+ // filter = false;
+
+ // Get list of roles per user, then add to Roles as we go
+ HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
+ Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role);
+ if(rlurd.isOK()) {
+ for(UserRoleDAO.Data data : rlurd.value) {
+ userSet.add(data);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES);
+ // Checked for permission
+ mapper.userRoles(trans, userSet, users);
+ return Result.ok(users);
+ }
+ /**
+ * getUserRolesByRole
+ */
+ @ApiDoc(
+ method = GET,
+ path = "/authz/userRoles/user/:user",
+ params = {"role|string|true"},
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "List all UserRoles for :user",
+ }
+ )
+ @Override
+ public Result<USERROLES> getUserRolesByUser(AuthzTrans trans, String user) {
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank("User",user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ // Get list of roles per user, then add to Roles as we go
+ Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user);
+ if(rlurd.notOK()) {
+ return Result.err(rlurd);
+ }
+ @SuppressWarnings("unchecked")
+ USERROLES users = (USERROLES) mapper.newInstance(API.USER_ROLES);
+ // Checked for permission
+ mapper.userRoles(trans, rlurd.value, users);
+ return Result.ok(users);
+ }
+
+
+ @ApiDoc(
+ method = PUT,
+ path = "/authz/userRole/user",
+ params = {},
+ expectedCode = 200,
+ errorCodes = {403,404,406},
+ text = { "Set a User's roles to the roles specified in the UserRoleRequest object.",
+ "WARNING: Roles supplied will be the ONLY roles attached to this user",
+ "If no roles are supplied, user's roles are reset."
+ }
+ )
+ @Override
+ public Result<Void> resetRolesForUser(AuthzTrans trans, REQUEST rreq) {
+ Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq);
+ final Validator v = new Validator();
+ if(rurdd.notOKorIsEmpty()) {
+ return Result.err(rurdd);
+ }
+ if (v.user(trans.org(), rurdd.value.user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Set<String> currRoles = new HashSet<String>();
+ Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, rurdd.value.user);
+ if(rlurd.isOK()) {
+ for(UserRoleDAO.Data data : rlurd.value) {
+ currRoles.add(data.role);
+ }
+ }
+
+ Result<Void> rv = null;
+ String[] roles;
+ if(rurdd.value.role==null) {
+ roles = new String[0];
+ } else {
+ roles = rurdd.value.role.split(",");
+ }
+
+ for (String role : roles) {
+ if (v.role(role).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
+ if(rrdd.notOK()) {
+ return Result.err(rrdd);
+ }
+
+ rurdd.value.role(rrdd.value);
+
+ Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), rrdd.value,Access.write);
+ if (nsd.notOK()) {
+ return Result.err(nsd);
+ }
+ Result<NsDAO.Data> nsr = ques.deriveNs(trans, role);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+
+ if(currRoles.contains(role)) {
+ currRoles.remove(role);
+ } else {
+ rv = func.addUserRole(trans, rurdd.value);
+ if (rv.notOK()) {
+ return rv;
+ }
+ }
+ }
+
+ for (String role : currRoles) {
+ rurdd.value.role(trans,ques,role);
+ rv = ques.userRoleDAO.delete(trans, rurdd.value, true);
+ if(rv.notOK()) {
+ trans.info().log(rurdd.value.user,"/",rurdd.value.role, "expected to be deleted, but does not exist");
+ // return rv; // if it doesn't exist, don't error out
+ }
+
+ }
+
+ return Result.ok();
+
+ }
+
+ @ApiDoc(
+ method = PUT,
+ path = "/authz/userRole/role",
+ params = {},
+ expectedCode = 200,
+ errorCodes = {403,404,406},
+ text = { "Set a Role's users to the users specified in the UserRoleRequest object.",
+ "WARNING: Users supplied will be the ONLY users attached to this role",
+ "If no users are supplied, role's users are reset."
+ }
+ )
+ @Override
+ public Result<Void> resetUsersForRole(AuthzTrans trans, REQUEST rreq) {
+ Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq);
+ if(rurdd.notOKorIsEmpty()) {
+ return Result.err(rurdd);
+ }
+ final Validator v = new Validator();
+ if (v.user_role(rurdd.value).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ RoleDAO.Data rd = RoleDAO.Data.decode(rurdd.value);
+
+ Result<NsDAO.Data> nsd = ques.mayUser(trans, trans.user(), rd, Access.write);
+ if (nsd.notOK()) {
+ return Result.err(nsd);
+ }
+
+ Result<NsDAO.Data> nsr = ques.deriveNs(trans, rurdd.value.role);
+ if(nsr.notOKorIsEmpty()) {
+ return Result.err(nsr);
+ }
+
+ Set<String> currUsers = new HashSet<String>();
+ Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, rurdd.value.role);
+ if(rlurd.isOK()) {
+ for(UserRoleDAO.Data data : rlurd.value) {
+ currUsers.add(data.user);
+ }
+ }
+
+ // found when connected remotely to DEVL, can't replicate locally
+ // inconsistent errors with cmd: role user setTo [nothing]
+ // deleteUserRole --> read --> get --> cacheIdx(?)
+ // sometimes returns idx for last added user instead of user passed in
+ // cache bug?
+
+
+ Result<Void> rv = null;
+ String[] users = {};
+ if (rurdd.value.user != null) {
+ users = rurdd.value.user.split(",");
+ }
+
+ for (String user : users) {
+ if (v.user(trans.org(), user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ rurdd.value.user = user;
+
+ if(currUsers.contains(user)) {
+ currUsers.remove(user);
+ } else {
+ rv = func.addUserRole(trans, rurdd.value);
+ if (rv.notOK()) {
+ return rv;
+ }
+ }
+ }
+
+ for (String user : currUsers) {
+ rurdd.value.user = user;
+ rv = ques.userRoleDAO.delete(trans, rurdd.value, true);
+ if(rv.notOK()) {
+ trans.info().log(rurdd.value, "expected to be deleted, but not exists");
+ return rv;
+ }
+ }
+
+ return Result.ok();
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/userRole/extend/:user/:role",
+ params = { "user|string|true",
+ "role|string|true"
+ },
+ expectedCode = 200,
+ errorCodes = {403,404,406},
+ text = { "Extend the Expiration of this User Role by the amount set by Organization",
+ "Requestor must be allowed to modify the role"
+ }
+ )
+ @Override
+ public Result<Void> extendUserRole(AuthzTrans trans, String user, String role) {
+ Organization org = trans.org();
+ final Validator v = new Validator();
+ if(v.user(org, user)
+ .role(role)
+ .err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
+ if(rrdd.notOK()) {
+ return Result.err(rrdd);
+ }
+
+ Result<NsDAO.Data> rcr = ques.mayUser(trans, trans.user(), rrdd.value, Access.write);
+ boolean mayNotChange;
+ if((mayNotChange = rcr.notOK()) && !trans.futureRequested()) {
+ return Result.err(rcr);
+ }
+
+ Result<List<UserRoleDAO.Data>> rr = ques.userRoleDAO.read(trans, user,role);
+ if(rr.notOK()) {
+ return Result.err(rr);
+ }
+ for(UserRoleDAO.Data userRole : rr.value) {
+ if(mayNotChange) { // Function exited earlier if !trans.futureRequested
+ FutureDAO.Data fto = new FutureDAO.Data();
+ fto.target=UserRoleDAO.TABLE;
+ fto.memo = "Extend User ["+userRole.user+"] in Role ["+userRole.role+"]";
+ GregorianCalendar now = new GregorianCalendar();
+ fto.start = now.getTime();
+ fto.expires = org.expiration(now, Expiration.Future).getTime();
+ try {
+ fto.construct = userRole.bytify();
+ } catch (IOException e) {
+ trans.error().log(e, "Error while bytifying UserRole for Future");
+ return Result.err(e);
+ }
+
+ Result<List<Identity>> rfc = func.createFuture(trans, fto,
+ userRole.user+'|'+userRole.role, userRole.user, rcr.value, "U");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing",
+ userRole.user,
+ userRole.role);
+ } else {
+ return Result.err(rfc);
+ }
+ } else {
+ return func.extendUserRole(trans, userRole, false);
+ }
+ }
+ return Result.err(Result.ERR_NotFound,"This user and role doesn't exist");
+ }
+
+ @ApiDoc(
+ method = DELETE,
+ path = "/authz/userRole/:user/:role",
+ params = { "user|string|true",
+ "role|string|true"
+ },
+ expectedCode = 200,
+ errorCodes = {403,404,406},
+ text = { "Remove Role :role from User :user."
+ }
+ )
+ @Override
+ public Result<Void> deleteUserRole(AuthzTrans trans, String usr, String role) {
+ Validator val = new Validator();
+ if(val.nullOrBlank("User", usr)
+ .nullOrBlank("Role", role).err()) {
+ return Result.err(Status.ERR_BadData, val.errs());
+ }
+
+ boolean mayNotChange;
+ Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role);
+ if(rrdd.notOK()) {
+ return Result.err(rrdd);
+ }
+
+ RoleDAO.Data rdd = rrdd.value;
+ // Make sure we don't delete the last owner
+ if(Question.OWNER.equals(rdd.name) && ques.countOwner(trans, usr, rdd.ns)<=1) {
+ return Result.err(Status.ERR_Denied,"You may not delete the last Owner of " + rdd.ns );
+ }
+
+ Result<NsDAO.Data> rns = ques.mayUser(trans, trans.user(), rdd, Access.write);
+ if(mayNotChange=rns.notOK()) {
+ if(!trans.futureRequested()) {
+ return Result.err(rns);
+ }
+ }
+
+ Result<List<UserRoleDAO.Data>> rulr;
+ if((rulr=ques.userRoleDAO.read(trans, usr, role)).notOKorIsEmpty()) {
+ return Result.err(Status.ERR_UserRoleNotFound, "User [ "+usr+" ] is not "
+ + "Assigned to the Role [ " + role + " ]");
+ }
+
+ UserRoleDAO.Data userRole = rulr.value.get(0);
+ if(mayNotChange) { // Function exited earlier if !trans.futureRequested
+ FutureDAO.Data fto = new FutureDAO.Data();
+ fto.target=UserRoleDAO.TABLE;
+ fto.memo = "Remove User ["+userRole.user+"] from Role ["+userRole.role+"]";
+ GregorianCalendar now = new GregorianCalendar();
+ fto.start = now.getTime();
+ fto.expires = trans.org().expiration(now, Expiration.Future).getTime();
+
+ Result<List<Identity>> rfc = func.createFuture(trans, fto,
+ userRole.user+'|'+userRole.role, userRole.user, rns.value, "D");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing",
+ userRole.user,
+ userRole.role);
+ } else {
+ return Result.err(rfc);
+ }
+ } else {
+ return ques.userRoleDAO.delete(trans, rulr.value.get(0), false);
+ }
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/userRole/:user/:role",
+ params = {"user|string|true",
+ "role|string|true"},
+ expectedCode = 200,
+ errorCodes = {403,404,406},
+ text = { "Returns the User (with Expiration date from listed User/Role) if it exists"
+ }
+ )
+ @Override
+ public Result<USERS> getUserInRole(AuthzTrans trans, String user, String role) {
+ final Validator v = new Validator();
+ if(v.role(role).nullOrBlank("User", user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+// Result<NsDAO.Data> ns = ques.deriveNs(trans, role);
+// if (ns.notOK()) return Result.err(ns);
+//
+// Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write);
+ // May calling user see by virtue of the Role
+ Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
+ if(rrdd.notOK()) {
+ return Result.err(rrdd);
+ }
+ Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+ HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
+ Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readUserInRole(trans, user, role);
+ if(rlurd.isOK()) {
+ for(UserRoleDAO.Data data : rlurd.value) {
+ userSet.add(data);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ USERS users = (USERS) mapper.newInstance(API.USERS);
+ mapper.users(trans, userSet, users);
+ return Result.ok(users);
+ }
+
+ @ApiDoc(
+ method = GET,
+ path = "/authz/users/role/:role",
+ params = {"user|string|true",
+ "role|string|true"},
+ expectedCode = 200,
+ errorCodes = {403,404,406},
+ text = { "Returns the User (with Expiration date from listed User/Role) if it exists"
+ }
+ )
+ @Override
+ public Result<USERS> getUsersByRole(AuthzTrans trans, String role) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("Role",role).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+// Result<NsDAO.Data> ns = ques.deriveNs(trans, role);
+// if (ns.notOK()) return Result.err(ns);
+//
+// Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write);
+ // May calling user see by virtue of the Role
+ Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
+ if(rrdd.notOK()) {
+ return Result.err(rrdd);
+ }
+ Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+ HashSet<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
+ Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role);
+ if(rlurd.isOK()) {
+ for(UserRoleDAO.Data data : rlurd.value) {
+ userSet.add(data);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ USERS users = (USERS) mapper.newInstance(API.USERS);
+ mapper.users(trans, userSet, users);
+ return Result.ok(users);
+ }
+
+ /**
+ * getUsersByPermission
+ */
+ @ApiDoc(
+ method = GET,
+ path = "/authz/users/perm/:type/:instance/:action",
+ params = { "type|string|true",
+ "instance|string|true",
+ "action|string|true"
+ },
+ expectedCode = 200,
+ errorCodes = {404,406},
+ text = { "List all Users that have Permission specified by :type :instance :action",
+ }
+ )
+ @Override
+ public Result<USERS> getUsersByPermission(AuthzTrans trans, String type, String instance, String action) {
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank("Type",type)
+ .nullOrBlank("Instance",instance)
+ .nullOrBlank("Action",action)
+ .err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<NsSplit> nss = ques.deriveNsSplit(trans, type);
+ if(nss.notOK()) {
+ return Result.err(nss);
+ }
+
+ Result<List<NsDAO.Data>> nsd = ques.nsDAO.read(trans, nss.value.ns);
+ if (nsd.notOK()) {
+ return Result.err(nsd);
+ }
+
+ boolean allInstance = ASTERIX.equals(instance);
+ boolean allAction = ASTERIX.equals(action);
+ // Get list of roles per Permission,
+ // Then loop through Roles to get Users
+ // Note: Use Sets to avoid processing or responding with Duplicates
+ Set<String> roleUsed = new HashSet<String>();
+ Set<UserRoleDAO.Data> userSet = new HashSet<UserRoleDAO.Data>();
+
+ if(!nss.isEmpty()) {
+ Result<List<PermDAO.Data>> rlp = ques.permDAO.readByType(trans, nss.value.ns, nss.value.name);
+ if(rlp.isOKhasData()) {
+ for(PermDAO.Data pd : rlp.value) {
+ if((allInstance || pd.instance.equals(instance)) &&
+ (allAction || pd.action.equals(action))) {
+ if(ques.mayUser(trans, trans.user(),pd,Access.read).isOK()) {
+ for(String role : pd.roles) {
+ if(!roleUsed.contains(role)) { // avoid evaluating Role many times
+ roleUsed.add(role);
+ Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role.replace('|', '.'));
+ if(rlurd.isOKhasData()) {
+ for(UserRoleDAO.Data urd : rlurd.value) {
+ userSet.add(urd);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ @SuppressWarnings("unchecked")
+ USERS users = (USERS) mapper.newInstance(API.USERS);
+ mapper.users(trans, userSet, users);
+ return Result.ok(users);
+ }
+
+ /***********************************
+ * HISTORY
+ ***********************************/
+ @Override
+ public Result<HISTORY> getHistoryByUser(final AuthzTrans trans, String user, final int[] yyyymm, final int sort) {
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank("User",user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<NsDAO.Data> rnd;
+ // Users may look at their own data
+ if(trans.user().equals(user)) {
+ // Users may look at their own data
+ } else {
+ int at = user.indexOf('@');
+ if(at>=0 && trans.org().getRealm().equals(user.substring(at+1))) {
+ NsDAO.Data nsd = new NsDAO.Data();
+ nsd.name = Question.domain2ns(user);
+ rnd = ques.mayUser(trans, trans.user(), nsd, Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+ } else {
+ rnd = ques.validNSOfDomain(trans, user);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+ rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+ }
+ }
+ Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readByUser(trans, user, yyyymm);
+ if(resp.notOK()) {
+ return Result.err(resp);
+ }
+ return mapper.history(trans, resp.value,sort);
+ }
+
+ @Override
+ public Result<HISTORY> getHistoryByRole(AuthzTrans trans, String role, int[] yyyymm, final int sort) {
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank("Role",role).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role);
+ if(rrdd.notOK()) {
+ return Result.err(rrdd);
+ }
+
+ Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value, Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+ Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, role, "role", yyyymm);
+ if(resp.notOK()) {
+ return Result.err(resp);
+ }
+ return mapper.history(trans, resp.value,sort);
+ }
+
+ @Override
+ public Result<HISTORY> getHistoryByPerm(AuthzTrans trans, String type, int[] yyyymm, final int sort) {
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank("Type",type)
+ .err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ // May user see Namespace of Permission (since it's only one piece... we can't check for "is permission part of")
+ Result<NsDAO.Data> rnd = ques.deriveNs(trans,type);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+ rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+ Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, type, "perm", yyyymm);
+ if(resp.notOK()) {
+ return Result.err(resp);
+ }
+ return mapper.history(trans, resp.value,sort);
+ }
+
+ @Override
+ public Result<HISTORY> getHistoryByNS(AuthzTrans trans, String ns, int[] yyyymm, final int sort) {
+ final Validator v = new Validator(trans);
+ if(v.nullOrBlank("NS",ns)
+ .err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+ rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read);
+ if(rnd.notOK()) {
+ return Result.err(rnd);
+ }
+
+ Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, ns, "ns", yyyymm);
+ if(resp.notOK()) {
+ return Result.err(resp);
+ }
+ return mapper.history(trans, resp.value,sort);
+ }
+
+/***********************************
+ * DELEGATE
+ ***********************************/
+ @Override
+ public Result<Void> createDelegate(final AuthzTrans trans, REQUEST base) {
+ return createOrUpdateDelegate(trans, base, Question.Access.create);
+ }
+
+ @Override
+ public Result<Void> updateDelegate(AuthzTrans trans, REQUEST base) {
+ return createOrUpdateDelegate(trans, base, Question.Access.write);
+ }
+
+
+ private Result<Void> createOrUpdateDelegate(final AuthzTrans trans, REQUEST base, final Access access) {
+ final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base);
+ final Validator v = new Validator();
+ if(v.delegate(trans.org(),rd).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ final DelegateDAO.Data dd = rd.value;
+
+ Result<List<DelegateDAO.Data>> ddr = ques.delegateDAO.read(trans, dd);
+ if(access==Access.create && ddr.isOKhasData()) {
+ return Result.err(Status.ERR_ConflictAlreadyExists, "[%s] already delegates to [%s]", dd.user, ddr.value.get(0).delegate);
+ } else if(access!=Access.create && ddr.notOKorIsEmpty()) {
+ return Result.err(Status.ERR_NotFound, "[%s] does not have a Delegate Record to [%s].",dd.user,access.name());
+ }
+ Result<Void> rv = ques.mayUser(trans, dd, access);
+ if(rv.notOK()) {
+ return rv;
+ }
+
+ Result<FutureDAO.Data> fd = mapper.future(trans,DelegateDAO.TABLE,base, dd, false,
+ new Mapper.Memo() {
+ @Override
+ public String get() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(access.name());
+ sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
+ sb.append("Delegate ");
+ sb.append(access==Access.create?"[":"to [");
+ sb.append(rd.value.delegate);
+ sb.append("] for [");
+ sb.append(rd.value.user);
+ sb.append(']');
+ return sb.toString();
+ }
+ },
+ new MayChange() {
+ @Override
+ public Result<?> mayChange() {
+ return Result.ok(); // Validate in code above
+ }
+ });
+
+ switch(fd.status) {
+ case OK:
+ Result<List<Identity>> rfc = func.createFuture(trans, fd.value,
+ dd.user, trans.user(),null, access==Access.create?"C":"U");
+ if(rfc.isOK()) {
+ return Result.err(Status.ACC_Future, "Delegate for [%s]",
+ dd.user);
+ } else {
+ return Result.err(rfc);
+ }
+ case Status.ACC_Now:
+ if(access==Access.create) {
+ Result<DelegateDAO.Data> rdr = ques.delegateDAO.create(trans, dd);
+ if(rdr.isOK()) {
+ return Result.ok();
+ } else {
+ return Result.err(rdr);
+ }
+ } else {
+ return ques.delegateDAO.update(trans, dd);
+ }
+ default:
+ return Result.err(fd);
+ }
+ }
+
+ @Override
+ public Result<Void> deleteDelegate(AuthzTrans trans, REQUEST base) {
+ final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base);
+ final Validator v = new Validator();
+ if(v.notOK(rd).nullOrBlank("User", rd.value.user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<List<DelegateDAO.Data>> ddl;
+ if((ddl=ques.delegateDAO.read(trans, rd.value)).notOKorIsEmpty()) {
+ return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate");
+ }
+ final DelegateDAO.Data dd = ddl.value.get(0);
+ Result<Void> rv = ques.mayUser(trans, dd, Access.write);
+ if(rv.notOK()) {
+ return rv;
+ }
+
+ return ques.delegateDAO.delete(trans, dd, false);
+ }
+
+ @Override
+ public Result<Void> deleteDelegate(AuthzTrans trans, String userName) {
+ DelegateDAO.Data dd = new DelegateDAO.Data();
+ final Validator v = new Validator();
+ if(v.nullOrBlank("User", userName).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ dd.user = userName;
+ Result<List<DelegateDAO.Data>> ddl;
+ if((ddl=ques.delegateDAO.read(trans, dd)).notOKorIsEmpty()) {
+ return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate");
+ }
+ dd = ddl.value.get(0);
+ Result<Void> rv = ques.mayUser(trans, dd, Access.write);
+ if(rv.notOK()) {
+ return rv;
+ }
+
+ return ques.delegateDAO.delete(trans, dd, false);
+ }
+
+ @Override
+ public Result<DELGS> getDelegatesByUser(AuthzTrans trans, String user) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("User", user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ DelegateDAO.Data ddd = new DelegateDAO.Data();
+ ddd.user = user;
+ ddd.delegate = null;
+ Result<Void> rv = ques.mayUser(trans, ddd, Access.read);
+ if(rv.notOK()) {
+ return Result.err(rv);
+ }
+
+ TimeTaken tt = trans.start("Get delegates for a user", Env.SUB);
+
+ Result<List<DelegateDAO.Data>> dbDelgs = ques.delegateDAO.read(trans, user);
+ try {
+ if (dbDelgs.isOKhasData()) {
+ return mapper.delegate(dbDelgs.value);
+ } else {
+ return Result.err(Status.ERR_DelegateNotFound,"No Delegate found for [%s]",user);
+ }
+ } finally {
+ tt.done();
+ }
+ }
+
+ @Override
+ public Result<DELGS> getDelegatesByDelegate(AuthzTrans trans, String delegate) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("Delegate", delegate).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ DelegateDAO.Data ddd = new DelegateDAO.Data();
+ ddd.user = delegate;
+ Result<Void> rv = ques.mayUser(trans, ddd, Access.read);
+ if(rv.notOK()) {
+ return Result.err(rv);
+ }
+
+ TimeTaken tt = trans.start("Get users for a delegate", Env.SUB);
+
+ Result<List<DelegateDAO.Data>> dbDelgs = ques.delegateDAO.readByDelegate(trans, delegate);
+ try {
+ if (dbDelgs.isOKhasData()) {
+ return mapper.delegate(dbDelgs.value);
+ } else {
+ return Result.err(Status.ERR_DelegateNotFound,"Delegate [%s] is not delegating for anyone.",delegate);
+ }
+ } finally {
+ tt.done();
+ }
+ }
+
+/***********************************
+ * APPROVAL
+ ***********************************/
+ @Override
+ public Result<Void> updateApproval(AuthzTrans trans, APPROVALS approvals) {
+ Result<List<ApprovalDAO.Data>> rlad = mapper.approvals(approvals);
+ if(rlad.notOK()) {
+ return Result.err(rlad);
+ }
+ int numApprs = rlad.value.size();
+ if(numApprs<1) {
+ return Result.err(Status.ERR_NoApprovals,"No Approvals sent for Updating");
+ }
+ int numProcessed = 0;
+ String user = trans.user();
+
+ Result<List<ApprovalDAO.Data>> curr;
+ for(ApprovalDAO.Data updt : rlad.value) {
+ if(updt.ticket!=null) {
+ curr = ques.approvalDAO.readByTicket(trans, updt.ticket);
+ } else if(updt.id!=null) {
+ curr = ques.approvalDAO.read(trans, updt);
+ } else if(updt.approver!=null) {
+ curr = ques.approvalDAO.readByApprover(trans, updt.approver);
+ } else {
+ return Result.err(Status.ERR_BadData,"Approvals need ID, Ticket or Approval data to update");
+ }
+ if(curr.isOKhasData()) {
+ for(ApprovalDAO.Data cd : curr.value){
+ // Check for right record. Need ID, or (Ticket&Trans.User==Appr)
+ // If Default ID
+ boolean delegatedAction = ques.isDelegated(trans, user, cd.approver);
+ String delegator = cd.approver;
+ if(updt.id!=null ||
+ (updt.ticket!=null && user.equals(cd.approver)) ||
+ (updt.ticket!=null && delegatedAction)) {
+ if(updt.ticket.equals(cd.ticket)) {
+ cd.id = changed(updt.id,cd.id);
+ cd.ticket = changed(updt.ticket,cd.ticket);
+ cd.user = changed(updt.user,cd.user);
+ cd.approver = changed(updt.approver,cd.approver);
+ cd.type = changed(updt.type,cd.type);
+ cd.status = changed(updt.status,cd.status);
+ cd.memo = changed(updt.memo,cd.memo);
+ cd.operation = changed(updt.operation,cd.operation);
+ cd.updated = changed(updt.updated,cd.updated);
+ ques.approvalDAO.update(trans, cd);
+ Result<Void> rv = func.performFutureOp(trans, cd);
+ if (rv.isOK()) {
+ if (delegatedAction) {
+ trans.audit().log("actor=",user,",action=",updt.status,",operation=\"",cd.memo,
+ '"',",requestor=",cd.user,",delegator=",delegator);
+ }
+ if (!delegatedAction && cd.status.equalsIgnoreCase("denied")) {
+ trans.audit().log("actor=",trans.user(),",action=denied,operation=\"",cd.memo,'"',",requestor=",cd.user);
+ }
+ rv = ques.approvalDAO.delete(trans, cd, false);
+ }
+ ++numProcessed;
+
+ }
+ }
+ }
+ }
+ }
+
+ if(numApprs==numProcessed) {
+ return Result.ok();
+ }
+ return Result.err(Status.ERR_ActionNotCompleted,numProcessed + " out of " + numApprs + " completed");
+
+ }
+
+ private<T> T changed(T src, T dflt) {
+ if(src!=null) {
+ return src;
+ }
+ return dflt;
+ }
+
+ @Override
+ public Result<APPROVALS> getApprovalsByUser(AuthzTrans trans, String user) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("User", user).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByUser(trans, user);
+ if(rapd.isOK()) {
+ return mapper.approvals(rapd.value);
+ } else {
+ return Result.err(rapd);
+ }
+}
+
+ @Override
+ public Result<APPROVALS> getApprovalsByTicket(AuthzTrans trans, String ticket) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("Ticket", ticket).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+ UUID uuid;
+ try {
+ uuid = UUID.fromString(ticket);
+ } catch (IllegalArgumentException e) {
+ return Result.err(Status.ERR_BadData,e.getMessage());
+ }
+
+ Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByTicket(trans, uuid);
+ if(rapd.isOK()) {
+ return mapper.approvals(rapd.value);
+ } else {
+ return Result.err(rapd);
+ }
+ }
+
+ @Override
+ public Result<APPROVALS> getApprovalsByApprover(AuthzTrans trans, String approver) {
+ final Validator v = new Validator();
+ if(v.nullOrBlank("Approver", approver).err()) {
+ return Result.err(Status.ERR_BadData,v.errs());
+ }
+
+ List<ApprovalDAO.Data> listRapds = new ArrayList<ApprovalDAO.Data>();
+
+ Result<List<ApprovalDAO.Data>> myRapd = ques.approvalDAO.readByApprover(trans, approver);
+ if(myRapd.notOK()) {
+ return Result.err(myRapd);
+ }
+
+ listRapds.addAll(myRapd.value);
+
+ Result<List<DelegateDAO.Data>> delegatedFor = ques.delegateDAO.readByDelegate(trans, approver);
+ if (delegatedFor.isOK()) {
+ for (DelegateDAO.Data dd : delegatedFor.value) {
+ if (dd.expires.after(new Date())) {
+ String delegator = dd.user;
+ Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByApprover(trans, delegator);
+ if (rapd.isOK()) {
+ for (ApprovalDAO.Data d : rapd.value) {
+ if (!d.user.equals(trans.user())) {
+ listRapds.add(d);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return mapper.approvals(listRapds);
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.service.AuthzService#clearCache(org.onap.aaf.authz.env.AuthzTrans, java.lang.String)
+ */
+ @Override
+ public Result<Void> cacheClear(AuthzTrans trans, String cname) {
+ if(ques.isGranted(trans,trans.user(),Define.ROOT_NS,CACHE,cname,"clear")) {
+ return ques.clearCache(trans,cname);
+ }
+ return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.cache|%s|clear",
+ trans.user(),Define.ROOT_NS,cname);
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.service.AuthzService#cacheClear(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.Integer)
+ */
+ @Override
+ public Result<Void> cacheClear(AuthzTrans trans, String cname, int[] segment) {
+ if(ques.isGranted(trans,trans.user(),Define.ROOT_NS,CACHE,cname,"clear")) {
+ Result<Void> v=null;
+ for(int i: segment) {
+ v=ques.cacheClear(trans,cname,i);
+ }
+ if(v!=null) {
+ return v;
+ }
+ }
+ return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.cache|%s|clear",
+ trans.user(),Define.ROOT_NS,cname);
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.service.AuthzService#dbReset(org.onap.aaf.authz.env.AuthzTrans)
+ */
+ @Override
+ public void dbReset(AuthzTrans trans) {
+ ques.historyDAO.reportPerhapsReset(trans, null);
+ }
+
+}
+
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/AuthzService.java b/authz-service/src/main/java/org/onap/aaf/authz/service/AuthzService.java new file mode 100644 index 00000000..27a000f3 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/AuthzService.java @@ -0,0 +1,748 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service;
+
+import java.util.Date;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.mapper.Mapper;
+import org.onap.aaf.dao.DAOException;
+import org.onap.aaf.dao.aaf.cass.NsType;
+
+public interface AuthzService<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> {
+ public Mapper<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper();
+
+/***********************************
+ * NAMESPACE
+ ***********************************/
+ /**
+ *
+ * @param trans
+ * @param user
+ * @param ns
+ * @return
+ * @throws DAOException
+ * @throws
+ */
+ public Result<Void> createNS(AuthzTrans trans, REQUEST request, NsType type);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @return
+ */
+ public Result<Void> addAdminNS(AuthzTrans trans, String ns, String id);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @return
+ */
+ public Result<Void> delAdminNS(AuthzTrans trans, String ns, String id);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @param id
+ * @return
+ */
+ public Result<Void> addResponsibleNS(AuthzTrans trans, String ns, String id);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @param id
+ * @return
+ */
+ public Result<Void> delResponsibleNS(AuthzTrans trans, String ns, String id);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @param key
+ * @param value
+ * @return
+ */
+ public Result<Void> createNsAttrib(AuthzTrans trans, String ns, String key, String value);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @param key
+ * @param value
+ * @return
+ */
+ public Result<?> updateNsAttrib(AuthzTrans trans, String ns, String key, String value);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @param key
+ * @return
+ */
+ public Result<Void> deleteNsAttrib(AuthzTrans trans, String ns, String key);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @param key
+ * @return
+ */
+ public Result<KEYS> readNsByAttrib(AuthzTrans trans, String key);
+
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @return
+ */
+ public Result<NSS> getNSbyName(AuthzTrans trans, String ns);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @return
+ */
+ public Result<NSS> getNSbyAdmin(AuthzTrans trans, String user, boolean full);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @return
+ */
+ public Result<NSS> getNSbyResponsible(AuthzTrans trans, String user, boolean full);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @return
+ */
+ public Result<NSS> getNSbyEither(AuthzTrans trans, String user, boolean full);
+
+ /**
+ *
+ * @param trans
+ * @param parent
+ * @return
+ */
+ public Result<NSS> getNSsChildren(AuthzTrans trans, String parent);
+
+ /**
+ *
+ * @param trans
+ * @param req
+ * @return
+ */
+ public Result<Void> updateNsDescription(AuthzTrans trans, REQUEST req);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @param user
+ * @return
+ * @throws DAOException
+ */
+ public Result<Void> deleteNS(AuthzTrans trans, String ns);
+
+/***********************************
+ * PERM
+ ***********************************/
+ /**
+ *
+ * @param trans
+ * @param rreq
+ * @return
+ * @throws DAOException
+ * @throws MappingException
+ */
+ public Result<Void> createPerm(AuthzTrans trans, REQUEST rreq);
+
+ /**
+ *
+ * @param trans
+ * @param childPerm
+ * @return
+ * @throws DAOException
+ */
+ public Result<PERMS> getPermsByType(AuthzTrans trans, String perm);
+
+ /**
+ *
+ * @param trans
+ * @param type
+ * @param instance
+ * @param action
+ * @return
+ */
+ public Result<PERMS> getPermsByName(AuthzTrans trans, String type,
+ String instance, String action);
+
+ /**
+ * Gets all the permissions for a user across all the roles it is assigned to
+ * @param userName
+ * @return
+ * @throws Exception
+ * @throws Exception
+ */
+ public Result<PERMS> getPermsByUser(AuthzTrans trans, String userName);
+
+ /**
+ * Gets all the permissions for a user across all the roles it is assigned to
+ *
+ * Add AAF Perms representing the "MayUser" calls if
+ * 1) Allowed
+ * 2) User has equivalent permission
+ *
+ * @param userName
+ * @return
+ * @throws Exception
+ * @throws Exception
+ */
+ public Result<PERMS> getPermsByUser(AuthzTrans trans, PERMS perms, String userName);
+
+ /**
+ *
+ * Gets all the permissions for a user across all the roles it is assigned to
+ *
+ * @param roleName
+ * @return
+ * @throws Exception
+ */
+ public Result<PERMS> getPermsByRole(AuthzTrans trans, String roleName);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @return
+ */
+ public Result<PERMS> getPermsByNS(AuthzTrans trans, String ns);
+
+ /**
+ * rename permission
+ *
+ * @param trans
+ * @param rreq
+ * @param isRename
+ * @param origType
+ * @param origInstance
+ * @param origAction
+ * @return
+ */
+ public Result<Void> renamePerm(AuthzTrans trans, REQUEST rreq, String origType, String origInstance, String origAction);
+
+ /**
+ *
+ * @param trans
+ * @param req
+ * @return
+ */
+ public Result<Void> updatePermDescription(AuthzTrans trans, REQUEST req);
+
+ /**
+ *
+ * @param trans
+ * @param from
+ * @return
+ */
+ public Result<Void> resetPermRoles(AuthzTrans trans, REQUEST from);
+
+ /**
+ *
+ * @param trans
+ * @param from
+ * @return
+ * @throws Exception
+ */
+ public Result<Void> deletePerm(AuthzTrans trans, REQUEST from);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @param perm
+ * @param type
+ * @param action
+ * @return
+ * @throws Exception
+ */
+ Result<Void> deletePerm(AuthzTrans trans, String perm, String type, String action);
+
+/***********************************
+ * ROLE
+ ***********************************/
+ /**
+ *
+ * @param trans
+ * @param user
+ * @param role
+ * @param approvers
+ * @return
+ * @throws DAOException
+ * @throws Exception
+ */
+ public Result<Void> createRole(AuthzTrans trans, REQUEST req);
+
+ /**
+ *
+ * @param trans
+ * @param role
+ * @return
+ */
+ public Result<ROLES> getRolesByName(AuthzTrans trans, String role);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @return
+ * @throws DAOException
+ */
+ public Result<ROLES> getRolesByUser(AuthzTrans trans, String user);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @return
+ */
+ public Result<ROLES> getRolesByNS(AuthzTrans trans, String user);
+
+ /**
+ *
+ * @param trans
+ * @param name
+ * @return
+ */
+ public Result<ROLES> getRolesByNameOnly(AuthzTrans trans, String name);
+
+ /**
+ *
+ * @param trans
+ * @param type
+ * @param instance
+ * @param action
+ * @return
+ */
+ public Result<ROLES> getRolesByPerm(AuthzTrans trans, String type, String instance, String action);
+
+ /**
+ *
+ * @param trans
+ * @param req
+ * @return
+ */
+ public Result<Void> updateRoleDescription(AuthzTrans trans, REQUEST req);
+
+ /**
+ *
+ * @param trans
+ * @param rreq
+ * @return
+ * @throws DAOException
+ */
+ public Result<Void> addPermToRole(AuthzTrans trans, REQUEST rreq);
+
+
+ /**
+ *
+ * @param trans
+ * @param rreq
+ * @return
+ * @throws DAOException
+ */
+ Result<Void> delPermFromRole(AuthzTrans trans, REQUEST rreq);
+
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @param role
+ * @return
+ * @throws DAOException
+ * @throws MappingException
+ */
+ public Result<Void> deleteRole(AuthzTrans trans, String role);
+
+ /**
+ *
+ * @param trans
+ * @param req
+ * @return
+ */
+ public Result<Void> deleteRole(AuthzTrans trans, REQUEST req);
+
+/***********************************
+ * CRED
+ ***********************************/
+
+ /**
+ *
+ * @param trans
+ * @param from
+ * @return
+ */
+ Result<Void> createUserCred(AuthzTrans trans, REQUEST from);
+
+ /**
+ *
+ * @param trans
+ * @param from
+ * @return
+ */
+ Result<Void> changeUserCred(AuthzTrans trans, REQUEST from);
+
+ /**
+ *
+ * @param trans
+ * @param from
+ * @param days
+ * @return
+ */
+ Result<Void> extendUserCred(AuthzTrans trans, REQUEST from, String days);
+
+ /**
+ *
+ * @param trans
+ * @param ns
+ * @return
+ */
+ public Result<USERS> getCredsByNS(AuthzTrans trans, String ns);
+
+ /**
+ *
+ * @param trans
+ * @param id
+ * @return
+ */
+ public Result<USERS> getCredsByID(AuthzTrans trans, String id);
+
+ /**
+ *
+ * @param trans
+ * @param req
+ * @param id
+ * @return
+ */
+ public Result<CERTS> getCertInfoByID(AuthzTrans trans, HttpServletRequest req, String id);
+
+ /**
+ *
+ * @param trans
+ * @param credReq
+ * @return
+ */
+ public Result<Void> deleteUserCred(AuthzTrans trans, REQUEST credReq);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @return
+ * @throws Exception
+ */
+ public Result<Date> doesCredentialMatch(AuthzTrans trans, REQUEST credReq);
+
+ /**
+ *
+ * @param trans
+ * @param basicAuth
+ * @return
+ */
+ public Result<Date> validateBasicAuth(AuthzTrans trans, String basicAuth);
+
+ /**
+ *
+ * @param trans
+ * @param role
+ * @return
+ */
+ public Result<USERS> getUsersByRole(AuthzTrans trans, String role);
+
+ /**
+ *
+ * @param trans
+ * @param role
+ * @return
+ */
+ public Result<USERS> getUserInRole(AuthzTrans trans, String user, String role);
+
+ /**
+ *
+ * @param trans
+ * @param type
+ * @param instance
+ * @param action
+ * @return
+ */
+ public Result<USERS> getUsersByPermission(AuthzTrans trans,String type, String instance, String action);
+
+
+
+
+/***********************************
+ * USER-ROLE
+ ***********************************/
+ /**
+ *
+ * @param trans
+ * @param user
+ * @param request
+ * @return
+ * @throws Exception
+ */
+ public Result<Void> createUserRole(AuthzTrans trans, REQUEST request);
+
+ /**
+ *
+ * @param trans
+ * @param role
+ * @return
+ */
+ public Result<USERROLES> getUserRolesByRole(AuthzTrans trans, String role);
+
+ /**
+ *
+ * @param trans
+ * @param role
+ * @return
+ */
+ public Result<USERROLES> getUserRolesByUser(AuthzTrans trans, String user);
+
+ /**
+ *
+ * @param trans
+ * @param from
+ * @return
+ */
+ public Result<Void> resetRolesForUser(AuthzTrans trans, REQUEST from);
+
+ /**
+ *
+ * @param trans
+ * @param from
+ * @return
+ */
+ public Result<Void> resetUsersForRole(AuthzTrans trans, REQUEST from);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @param role
+ * @return
+ */
+ public Result<Void> extendUserRole(AuthzTrans trans, String user,
+ String role);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @param usr
+ * @param role
+ * @return
+ * @throws DAOException
+ */
+ public Result<Void> deleteUserRole(AuthzTrans trans, String usr, String role);
+
+
+
+/***********************************
+ * HISTORY
+ ***********************************/
+ /**
+ *
+ * @param trans
+ * @param user
+ * @param yyyymm
+ * @return
+ */
+ public Result<HISTORY> getHistoryByUser(AuthzTrans trans, String user, int[] yyyymm, int sort);
+
+ /**
+ *
+ * @param trans
+ * @param subj
+ * @param yyyymm
+ * @param sort
+ * @return
+ */
+ public Result<HISTORY> getHistoryByRole(AuthzTrans trans, String subj, int[] yyyymm, int sort);
+
+ /**
+ *
+ * @param trans
+ * @param subj
+ * @param yyyymm
+ * @param sort
+ * @return
+ */
+ public Result<HISTORY> getHistoryByPerm(AuthzTrans trans, String subj, int[] yyyymm, int sort);
+
+ /**
+ *
+ * @param trans
+ * @param subj
+ * @param yyyymm
+ * @param sort
+ * @return
+ */
+ public Result<HISTORY> getHistoryByNS(AuthzTrans trans, String subj, int[] yyyymm, int sort);
+
+/***********************************
+ * DELEGATE
+ ***********************************/
+ /**
+ *
+ * @param trans
+ * @param delegates
+ * @return
+ * @throws Exception
+ */
+ public Result<Void> createDelegate(AuthzTrans trans, REQUEST reqDelegate);
+
+ /**
+ *
+ * @param trans
+ * @param delegates
+ * @return
+ * @throws Exception
+ */
+ public Result<Void> updateDelegate(AuthzTrans trans, REQUEST reqDelegate);
+
+ /**
+ *
+ * @param trans
+ * @param userName
+ * @param delegate
+ * @return
+ * @throws Exception
+ */
+ public Result<Void> deleteDelegate(AuthzTrans trans, REQUEST reqDelegate);
+
+ /**
+ *
+ * @param trans
+ * @param userName
+ * @return
+ */
+ public Result<Void> deleteDelegate(AuthzTrans trans, String userName);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @return
+ * @throws Exception
+ */
+ public Result<DELGS> getDelegatesByUser(AuthzTrans trans, String user);
+
+
+ /**
+ *
+ * @param trans
+ * @param delegate
+ * @return
+ */
+ public Result<DELGS> getDelegatesByDelegate(AuthzTrans trans, String delegate);
+
+/***********************************
+ * APPROVAL
+ ***********************************/
+ /**
+ *
+ * @param trans
+ * @param user
+ * @param approver
+ * @param status
+ * @return
+ */
+ public Result<Void> updateApproval(AuthzTrans trans, APPROVALS approvals);
+
+ /**
+ *
+ * @param trans
+ * @param user
+ * @return
+ */
+ public Result<APPROVALS> getApprovalsByUser(AuthzTrans trans, String user);
+
+ /**
+ *
+ * @param trans
+ * @param ticket
+ * @return
+ */
+ public Result<APPROVALS> getApprovalsByTicket(AuthzTrans trans, String ticket);
+
+ /**
+ *
+ * @param trans
+ * @param approver
+ * @return
+ */
+ public Result<APPROVALS> getApprovalsByApprover(AuthzTrans trans, String approver);
+
+ /**
+ *
+ * @param trans
+ * @param cname
+ * @return
+ */
+ public Result<Void> cacheClear(AuthzTrans trans, String cname);
+
+ /**
+ *
+ * @param trans
+ * @param cname
+ * @param segment
+ * @return
+ */
+ public Result<Void> cacheClear(AuthzTrans trans, String cname, int[] segment);
+
+ /**
+ *
+ * @param trans
+ */
+ public void dbReset(AuthzTrans trans);
+
+
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/Code.java b/authz-service/src/main/java/org/onap/aaf/authz/service/Code.java new file mode 100644 index 00000000..097b6da2 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/Code.java @@ -0,0 +1,45 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.cssa.rserv.HttpCode;
+
+public abstract class Code extends HttpCode<AuthzTrans, AuthzFacade> implements Cloneable {
+ public boolean useJSON;
+
+ public Code(AuthzFacade facade, String description, boolean useJSON, String ... roles) {
+ super(facade, description, roles);
+ this.useJSON = useJSON;
+ }
+
+ public <D extends Code> D clone(AuthzFacade facade, boolean useJSON) throws Exception {
+ @SuppressWarnings("unchecked")
+ D d = (D)clone();
+ d.useJSON = useJSON;
+ d.context = facade;
+ return d;
+ }
+
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/MayChange.java b/authz-service/src/main/java/org/onap/aaf/authz/service/MayChange.java new file mode 100644 index 00000000..f697af5b --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/MayChange.java @@ -0,0 +1,33 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service;
+
+import org.onap.aaf.authz.layer.Result;
+
+/**
+ * There are several ways to determine if
+ *
+ */
+public interface MayChange {
+ public Result<?> mayChange();
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Api.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Api.java new file mode 100644 index 00000000..128096c2 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Api.java @@ -0,0 +1,93 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+import org.onap.aaf.cssa.rserv.HttpMethods;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+import org.onap.aaf.cadi.Symm;
+
+/**
+ * API Apis
+ *
+ */
+public class API_Api {
+ // Hide Public Constructor
+ private API_Api() {}
+
+ /**
+ * Normal Init level APIs
+ *
+ * @param authzAPI
+ * @param facade
+ * @throws Exception
+ */
+ public static void init(final AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+ ////////
+ // Overall APIs
+ ///////
+ authzAPI.route(HttpMethods.GET,"/api",API.API,new Code(facade,"Document API", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getAPI(trans,resp,authzAPI);
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ ////////
+ // Overall Examples
+ ///////
+ authzAPI.route(HttpMethods.GET,"/api/example/*",API.VOID,new Code(facade,"Document API", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ String pathInfo = req.getPathInfo();
+ int question = pathInfo.lastIndexOf('?');
+
+ pathInfo = pathInfo.substring(13, question<0?pathInfo.length():question);// IMPORTANT, this is size of "/api/example/"
+ String nameOrContextType=Symm.base64noSplit.decode(pathInfo);
+ Result<Void> r = context.getAPIExample(trans,resp,nameOrContextType,
+ question>=0 && "optional=true".equalsIgnoreCase(req.getPathInfo().substring(question+1))
+ );
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ }
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Approval.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Approval.java new file mode 100644 index 00000000..f69e6f70 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Approval.java @@ -0,0 +1,108 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import static org.onap.aaf.cssa.rserv.HttpMethods.GET;
+import static org.onap.aaf.cssa.rserv.HttpMethods.PUT;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+
+public class API_Approval {
+ // Hide Public Constructor
+ private API_Approval() {}
+
+ public static void init(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+
+ /**
+ * Get Approvals by User
+ */
+ authzAPI.route(GET, "/authz/approval/user/:user",API.APPROVALS,
+ new Code(facade,"Get Approvals by User", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getApprovalsByUser(trans, resp, pathParam(req,"user"));
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Get Approvals by Ticket
+ */
+ authzAPI.route(GET, "/authz/approval/ticket/:ticket",API.VOID,new Code(facade,"Get Approvals by Ticket ", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getApprovalsByTicket(trans, resp, pathParam(req,"ticket"));
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Get Approvals by Approver
+ */
+ authzAPI.route(GET, "/authz/approval/approver/:approver",API.APPROVALS,new Code(facade,"Get Approvals by Approver", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getApprovalsByApprover(trans, resp, pathParam(req,"approver"));
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+
+ /**
+ * Update an approval
+ */
+ authzAPI.route(PUT, "/authz/approval",API.APPROVALS,new Code(facade,"Update approvals", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.updateApproval(trans, req, resp);
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+ });
+ }
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Creds.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Creds.java new file mode 100644 index 00000000..7c1425b5 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Creds.java @@ -0,0 +1,278 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import static org.onap.aaf.cssa.rserv.HttpMethods.DELETE;
+import static org.onap.aaf.cssa.rserv.HttpMethods.GET;
+import static org.onap.aaf.cssa.rserv.HttpMethods.POST;
+import static org.onap.aaf.cssa.rserv.HttpMethods.PUT;
+
+import java.security.Principal;
+import java.util.Date;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.cadi.DirectAAFUserPass;
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+import org.onap.aaf.cssa.rserv.HttpMethods;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+import org.onap.aaf.cadi.CredVal;
+import org.onap.aaf.cadi.Symm;
+import org.onap.aaf.cadi.principal.BasicPrincipal;
+import org.onap.aaf.cadi.principal.X509Principal;
+import org.onap.aaf.inno.env.Env;
+
+/**
+ * Initialize All Dispatches related to Credentials (AUTHN)
+ *
+ */
+public class API_Creds {
+ // Hide Public Interface
+ private API_Creds() {}
+ // needed to validate Creds even when already Authenticated x509
+ /**
+ * TIME SENSITIVE APIs
+ *
+ * These will be first in the list
+ *
+ * @param env
+ * @param authzAPI
+ * @param facade
+ * @param directAAFUserPass
+ * @throws Exception
+ */
+ public static void timeSensitiveInit(Env env, AuthAPI authzAPI, AuthzFacade facade, final DirectAAFUserPass directAAFUserPass) throws Exception {
+ /**
+ * Basic Auth, quick Validation
+ *
+ * Responds OK or NotAuthorized
+ */
+ authzAPI.route(env, HttpMethods.GET, "/authn/basicAuth", new Code(facade,"Is given BasicAuth valid?",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Principal p = trans.getUserPrincipal();
+ if (p instanceof BasicPrincipal) {
+ // the idea is that if call is made with this credential, and it's a BasicPrincipal, it's ok
+ // otherwise, it wouldn't have gotten here.
+ resp.setStatus(HttpStatus.OK_200);
+ } else if (p instanceof X509Principal) {
+ // have to check Basic Auth here, because it might be CSP.
+ String ba = req.getHeader("Authorization");
+ if(ba.startsWith("Basic ")) {
+ String decoded = Symm.base64noSplit.decode(ba.substring(6));
+ int colon = decoded.indexOf(':');
+ if(directAAFUserPass.validate(
+ decoded.substring(0,colon),
+ CredVal.Type.PASSWORD ,
+ decoded.substring(colon+1).getBytes())) {
+
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ resp.setStatus(HttpStatus.FORBIDDEN_403);
+ }
+ }
+ } else if(p == null) {
+ trans.error().log("Transaction not Authenticated... no Principal");
+ resp.setStatus(HttpStatus.FORBIDDEN_403);
+ } else {
+ trans.checkpoint("Basic Auth Check Failed: This wasn't a Basic Auth Trans");
+ // For Auth Security questions, we don't give any info to client on why failed
+ resp.setStatus(HttpStatus.FORBIDDEN_403);
+ }
+ }
+ },"text/plain");
+
+ /**
+ * returns whether a given Credential is valid
+ */
+ authzAPI.route(POST, "/authn/validate", API.CRED_REQ, new Code(facade,"Is given Credential valid?",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Date> r = context.doesCredentialMatch(trans, req, resp);
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ // For Security, we don't give any info out on why failed, other than forbidden
+ resp.setStatus(HttpStatus.FORBIDDEN_403);
+ }
+ }
+ });
+
+ /**
+ * returns whether a given Credential is valid
+ */
+ authzAPI.route(GET, "/authn/cert/id/:id", API.CERTS, new Code(facade,"Get Cert Info by ID",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getCertInfoByID(trans, req, resp, pathParam(req,":id") );
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ // For Security, we don't give any info out on why failed, other than forbidden
+ resp.setStatus(HttpStatus.FORBIDDEN_403);
+ }
+ }
+ });
+
+
+
+
+ }
+
+ /**
+ * Normal Init level APIs
+ *
+ * @param authzAPI
+ * @param facade
+ * @throws Exception
+ */
+ public static void init(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+ /**
+ * Create a new ID/Credential
+ */
+ authzAPI.route(POST,"/authn/cred",API.CRED_REQ,new Code(facade,"Add a New ID/Credential", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.createUserCred(trans, req);
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.CREATED_201);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * gets all credentials by Namespace
+ */
+ authzAPI.route(GET, "/authn/creds/ns/:ns", API.USERS, new Code(facade,"Get Creds for a Namespace",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getCredsByNS(trans, resp, pathParam(req, "ns"));
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+
+ });
+
+ /**
+ * gets all credentials by ID
+ */
+ authzAPI.route(GET, "/authn/creds/id/:id", API.USERS, new Code(facade,"Get Creds by ID",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getCredsByID(trans, resp, pathParam(req, "id"));
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+
+ });
+
+
+ /**
+ * Update ID/Credential (aka reset)
+ */
+ authzAPI.route(PUT,"/authn/cred",API.CRED_REQ,new Code(facade,"Update an ID/Credential", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.changeUserCred(trans, req);
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Extend ID/Credential
+ * This behavior will accelerate getting out of P1 outages due to ignoring renewal requests, or
+ * other expiration issues.
+ *
+ * Scenario is that people who are solving Password problems at night, are not necessarily those who
+ * know what the passwords are supposed to be. Also, changing Password, without changing Configurations
+ * using that password only exacerbates the P1 Issue.
+ */
+ authzAPI.route(PUT,"/authn/cred/:days",API.CRED_REQ,new Code(facade,"Extend an ID/Credential", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.extendUserCred(trans, req, pathParam(req, "days"));
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Delete a ID/Credential by Object
+ */
+ authzAPI.route(DELETE,"/authn/cred",API.CRED_REQ,new Code(facade,"Delete a Credential", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.deleteUserCred(trans, req);
+ if(r.isOK()) {
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ }
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Delegate.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Delegate.java new file mode 100644 index 00000000..6d382c57 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Delegate.java @@ -0,0 +1,154 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+import static org.onap.aaf.cssa.rserv.HttpMethods.DELETE;
+import static org.onap.aaf.cssa.rserv.HttpMethods.GET;
+import static org.onap.aaf.cssa.rserv.HttpMethods.POST;
+import static org.onap.aaf.cssa.rserv.HttpMethods.PUT;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+
+public class API_Delegate {
+ public static void init(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+ /**
+ * Add a delegate
+ */
+ authzAPI.route(POST, "/authz/delegate",API.DELG_REQ,new Code(facade,"Add a Delegate", true) {
+
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.createDelegate(trans, req, resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.CREATED_201);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Update a delegate
+ */
+ authzAPI.route(PUT, "/authz/delegate",API.DELG_REQ,new Code(facade,"Update a Delegate", true) {
+
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.updateDelegate(trans, req, resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * DELETE delegates for a user
+ */
+ authzAPI.route(DELETE, "/authz/delegate",API.DELG_REQ,new Code(facade,"Delete delegates for a user", true) {
+
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.deleteDelegate(trans, req, resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * DELETE a delegate
+ */
+ authzAPI.route(DELETE, "/authz/delegate/:user_name",API.VOID,new Code(facade,"Delete a Delegate", true) {
+
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.deleteDelegate(trans, pathParam(req, "user_name"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Read who is delegating for User
+ */
+ authzAPI.route(GET, "/authz/delegates/user/:user",API.DELGS,new Code(facade,"Get Delegates by User", true) {
+
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getDelegatesByUser(trans, pathParam(req, "user"), resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Read for whom the User is delegating
+ */
+ authzAPI.route(GET, "/authz/delegates/delegate/:delegate",API.DELGS,new Code(facade,"Get Delegates by Delegate", true) {
+
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getDelegatesByDelegate(trans, pathParam(req, "delegate"), resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ }
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_History.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_History.java new file mode 100644 index 00000000..d9db889c --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_History.java @@ -0,0 +1,239 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+import static org.onap.aaf.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 org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+import org.onap.aaf.dao.aaf.cass.Status;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+
+/**
+ * Pull certain types of History Info
+ *
+ * Specify yyyymm as
+ * single - 201504
+ * commas 201503,201504
+ * ranges 201501-201504
+ * combinations 201301,201401,201501-201504
+ *
+ *
+ */
+public class API_History {
+ /**
+ * Normal Init level APIs
+ *
+ * @param authzAPI
+ * @param facade
+ * @throws Exception
+ */
+ public static void init(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+ /**
+ * Get History
+ */
+ authzAPI.route(GET,"/authz/hist/user/:user",API.HISTORY,new Code(facade,"Get History by User", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ int[] years;
+ int descend;
+ try {
+ years = getYears(req);
+ descend = decending(req);
+ } catch(Exception e) {
+ context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage()));
+ return;
+ }
+
+ Result<Void> r = context.getHistoryByUser(trans, resp, pathParam(req,":user"),years,descend);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Get History by NS
+ */
+ authzAPI.route(GET,"/authz/hist/ns/:ns",API.HISTORY,new Code(facade,"Get History by Namespace", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ int[] years;
+ int descend;
+ try {
+ years = getYears(req);
+ descend = decending(req);
+ } catch(Exception e) {
+ context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage()));
+ return;
+ }
+
+ Result<Void> r = context.getHistoryByNS(trans, resp, pathParam(req,":ns"),years,descend);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Get History by Role
+ */
+ authzAPI.route(GET,"/authz/hist/role/:role",API.HISTORY,new Code(facade,"Get History by Role", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ int[] years;
+ int descend;
+ try {
+ years = getYears(req);
+ descend = decending(req);
+ } catch(Exception e) {
+ context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage()));
+ return;
+ }
+
+ Result<Void> r = context.getHistoryByRole(trans, resp, pathParam(req,":role"),years,descend);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Get History by Perm Type
+ */
+ authzAPI.route(GET,"/authz/hist/perm/:type",API.HISTORY,new Code(facade,"Get History by Perm Type", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ int[] years;
+ int descend;
+ try {
+ years = getYears(req);
+ descend = decending(req);
+ } catch(Exception e) {
+ context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage()));
+ return;
+ }
+
+ Result<Void> r = context.getHistoryByPerm(trans, resp, pathParam(req,":type"),years,descend);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+ }
+
+ // Check if Ascending
+ private static int decending(HttpServletRequest req) {
+ if("true".equalsIgnoreCase(req.getParameter("desc")))return -1;
+ if("true".equalsIgnoreCase(req.getParameter("asc")))return 1;
+ return 0;
+ }
+
+ // Get Common "yyyymm" parameter, or none
+ private static final SimpleDateFormat FMT = new SimpleDateFormat("yyyyMM");
+
+ private static int[] getYears(HttpServletRequest req) throws NumberFormatException {
+ String yyyymm = req.getParameter("yyyymm");
+ ArrayList<Integer> ai= new ArrayList<Integer>();
+ if(yyyymm==null) {
+ GregorianCalendar gc = new GregorianCalendar();
+ // three months is the default
+ for(int i=0;i<3;++i) {
+ ai.add(Integer.parseInt(FMT.format(gc.getTime())));
+ gc.add(GregorianCalendar.MONTH, -1);
+ }
+ } else {
+ for(String ym : yyyymm.split(",")) {
+ String range[] = ym.split("\\s*-\\s*");
+ switch(range.length) {
+ case 0:
+ break;
+ case 1:
+ if(!ym.endsWith("-")) {
+ ai.add(getNum(ym));
+ break;
+ } else {
+ range=new String[] {ym.substring(0, 6),FMT.format(new Date())};
+ }
+ default:
+ GregorianCalendar gc = new GregorianCalendar();
+ gc.set(GregorianCalendar.MONTH, Integer.parseInt(range[1].substring(4,6))-1);
+ gc.set(GregorianCalendar.YEAR, Integer.parseInt(range[1].substring(0,4)));
+ int end = getNum(FMT.format(gc.getTime()));
+
+ gc.set(GregorianCalendar.MONTH, Integer.parseInt(range[0].substring(4,6))-1);
+ gc.set(GregorianCalendar.YEAR, Integer.parseInt(range[0].substring(0,4)));
+ for(int i=getNum(FMT.format(gc.getTime()));i<=end;gc.add(GregorianCalendar.MONTH, 1),i=getNum(FMT.format(gc.getTime()))) {
+ ai.add(i);
+ }
+
+ }
+ }
+ }
+ if(ai.size()==0) {
+ throw new NumberFormatException(yyyymm + " is an invalid number or range");
+ }
+ Collections.sort(ai);
+ int ym[] = new int[ai.size()];
+ for(int i=0;i<ym.length;++i) {
+ ym[i]=ai.get(i);
+ }
+ return ym;
+ }
+
+ private static int getNum(String n) {
+ if(n==null || n.length()!=6) throw new NumberFormatException(n + " is not in YYYYMM format");
+ return Integer.parseInt(n);
+ }
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Mgmt.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Mgmt.java new file mode 100644 index 00000000..90ee6be7 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Mgmt.java @@ -0,0 +1,275 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+import static org.onap.aaf.cssa.rserv.HttpMethods.DELETE;
+import static org.onap.aaf.cssa.rserv.HttpMethods.POST;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.common.Define;
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+import org.onap.aaf.dao.aaf.cass.Status;
+import org.onap.aaf.dao.aaf.hl.Question;
+import org.onap.aaf.dao.session.SessionFilter;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf;
+import org.onap.aaf.inno.env.Trans;
+
+/**
+ * User Role APIs
+ *
+ */
+public class API_Mgmt {
+
+ private static final String SUCCESS = "SUCCESS";
+
+ /**
+ * Normal Init level APIs
+ *
+ * @param authzAPI
+ * @param facade
+ * @throws Exception
+ */
+ public static void init(final AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+
+ /**
+ * Clear Cache Segment
+ */
+ authzAPI.route(DELETE,"/mgmt/cache/:area/:segments",API.VOID,new Code(facade,"Clear Cache by Segment", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.cacheClear(trans, pathParam(req,"area"), pathParam(req,"segments"));
+ switch(r.status) {
+ case OK:
+ trans.checkpoint(SUCCESS,Trans.ALWAYS);
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Clear Cache
+ */
+ authzAPI.route(DELETE,"/mgmt/cache/:area",API.VOID,new Code(facade,"Clear Cache", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r;
+ String area;
+ r = context.cacheClear(trans, area=pathParam(req,"area"));
+ switch(r.status) {
+ case OK:
+ trans.audit().log("Cache " + area + " has been cleared by "+trans.user());
+ trans.checkpoint(SUCCESS,Trans.ALWAYS);
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Clear DB Sessions
+ */
+ authzAPI.route(DELETE,"/mgmt/dbsession",API.VOID,new Code(facade,"Clear DBSessions", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ try {
+ if(req.isUserInRole(Define.ROOT_NS+".db|pool|clear")) {
+ SessionFilter.clear();
+ context.dbReset(trans);
+
+ trans.audit().log("DB Sessions have been cleared by "+trans.user());
+
+ trans.checkpoint(SUCCESS,Trans.ALWAYS);
+ resp.setStatus(HttpStatus.OK_200);
+ return;
+ }
+ context.error(trans,resp,Result.err(Result.ERR_Denied,"%s is not allowed to clear dbsessions",trans.user()));
+ } catch(Exception e) {
+ trans.error().log(e, "clearing dbsession");
+ context.error(trans,resp,Result.err(e));
+ }
+ }
+ });
+
+ /**
+ * Deny an IP
+ */
+ authzAPI.route(POST, "/mgmt/deny/ip/:ip", API.VOID, new Code(facade,"Deny IP",true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ String ip = pathParam(req,":ip");
+ if(req.isUserInRole(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|ip")) {
+ if(DenialOfServiceTaf.denyIP(ip)) {
+ trans.audit().log(ip+" has been set to deny by "+trans.user());
+ trans.checkpoint(SUCCESS,Trans.ALWAYS);
+
+ resp.setStatus(HttpStatus.CREATED_201);
+ } else {
+ context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists,
+ ip + " is already being denied"));
+ }
+ } else {
+ trans.audit().log(trans.user(),"has attempted to deny",ip,"without authorization");
+ context.error(trans,resp,Result.err(Status.ERR_Denied,
+ trans.getUserPrincipal().getName() + " is not allowed to set IP Denial"));
+ }
+ }
+ });
+
+ /**
+ * Stop Denying an IP
+ */
+ authzAPI.route(DELETE, "/mgmt/deny/ip/:ip", API.VOID, new Code(facade,"Stop Denying IP",true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ String ip = pathParam(req,":ip");
+ if(req.isUserInRole(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|ip")) {
+ if(DenialOfServiceTaf.removeDenyIP(ip)) {
+ trans.audit().log(ip+" has been removed from denial by "+trans.user());
+ trans.checkpoint(SUCCESS,Trans.ALWAYS);
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,Result.err(Status.ERR_NotFound,
+ ip + " is not on the denial list"));
+ }
+ } else {
+ trans.audit().log(trans.user(),"has attempted to remove",ip," from being denied without authorization");
+ context.error(trans,resp,Result.err(Status.ERR_Denied,
+ trans.getUserPrincipal().getName() + " is not allowed to remove IP Denial"));
+ }
+ }
+ });
+
+ /**
+ * Deny an ID
+ */
+ authzAPI.route(POST, "/mgmt/deny/id/:id", API.VOID, new Code(facade,"Deny ID",true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ String id = pathParam(req,":id");
+ if(req.isUserInRole(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|id")) {
+ if(DenialOfServiceTaf.denyID(id)) {
+ trans.audit().log(id+" has been set to deny by "+trans.user());
+ trans.checkpoint(SUCCESS,Trans.ALWAYS);
+ resp.setStatus(HttpStatus.CREATED_201);
+ } else {
+ context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists,
+ id + " is already being denied"));
+ }
+ } else {
+ trans.audit().log(trans.user(),"has attempted to deny",id,"without authorization");
+ context.error(trans,resp,Result.err(Status.ERR_Denied,
+ trans.getUserPrincipal().getName() + " is not allowed to set ID Denial"));
+ }
+ }
+ });
+
+ /**
+ * Stop Denying an ID
+ */
+ authzAPI.route(DELETE, "/mgmt/deny/id/:id", API.VOID, new Code(facade,"Stop Denying ID",true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ String id = pathParam(req,":id");
+ if(req.isUserInRole(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|id")) {
+ if(DenialOfServiceTaf.removeDenyID(id)) {
+ trans.audit().log(id+" has been removed from denial by " + trans.user());
+ trans.checkpoint(SUCCESS,Trans.ALWAYS);
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,Result.err(Status.ERR_NotFound,
+ id + " is not on the denial list"));
+ }
+ } else {
+ trans.audit().log(trans.user(),"has attempted to remove",id," from being denied without authorization");
+ context.error(trans,resp,Result.err(Status.ERR_Denied,
+ trans.getUserPrincipal().getName() + " is not allowed to remove ID Denial"));
+ }
+ }
+ });
+
+ /**
+ * Deny an ID
+ */
+ authzAPI.route(POST, "/mgmt/log/id/:id", API.VOID, new Code(facade,"Special Log ID",true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ String id = pathParam(req,":id");
+ if(req.isUserInRole(Define.ROOT_NS+".log|"+Define.ROOT_COMPANY+"|id")) {
+ if(Question.specialLogOn(trans,id)) {
+ trans.audit().log(id+" has been set to special Log by "+trans.user());
+ trans.checkpoint(SUCCESS,Trans.ALWAYS);
+ resp.setStatus(HttpStatus.CREATED_201);
+ } else {
+ context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists,
+ id + " is already being special Logged"));
+ }
+ } else {
+ trans.audit().log(trans.user(),"has attempted to special Log",id,"without authorization");
+ context.error(trans,resp,Result.err(Status.ERR_Denied,
+ trans.getUserPrincipal().getName() + " is not allowed to set ID special Logging"));
+ }
+ }
+ });
+
+ /**
+ * Stop Denying an ID
+ */
+ authzAPI.route(DELETE, "/mgmt/log/id/:id", API.VOID, new Code(facade,"Stop Special Log ID",true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ String id = pathParam(req,":id");
+ if(req.isUserInRole(Define.ROOT_NS+".log|"+Define.ROOT_COMPANY+"|id")) {
+ if(Question.specialLogOff(trans,id)) {
+ trans.audit().log(id+" has been removed from special Logging by " + trans.user());
+ trans.checkpoint(SUCCESS,Trans.ALWAYS);
+ resp.setStatus(HttpStatus.OK_200);
+ } else {
+ context.error(trans,resp,Result.err(Status.ERR_NotFound,
+ id + " is not on the special Logging list"));
+ }
+ } else {
+ trans.audit().log(trans.user(),"has attempted to remove",id," from being special Logged without authorization");
+ context.error(trans,resp,Result.err(Status.ERR_Denied,
+ trans.getUserPrincipal().getName() + " is not allowed to remove ID special Logging"));
+ }
+ }
+ });
+
+
+ }
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_NS.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_NS.java new file mode 100644 index 00000000..d92302ce --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_NS.java @@ -0,0 +1,397 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+import static org.onap.aaf.cssa.rserv.HttpMethods.DELETE;
+import static org.onap.aaf.cssa.rserv.HttpMethods.GET;
+import static org.onap.aaf.cssa.rserv.HttpMethods.POST;
+import static org.onap.aaf.cssa.rserv.HttpMethods.PUT;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+import org.onap.aaf.dao.aaf.cass.NsType;
+import org.onap.aaf.dao.aaf.cass.Status;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+
+public class API_NS {
+ private static final String FULL = "full";
+ private static final String TRUE = "true";
+
+ public static void init(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+ /**
+ * puts a new Namespace in Authz DB
+ *
+ * TESTCASES: TC_NS1, TC_NSdelete1
+ */
+ authzAPI.route(POST,"/authz/ns",API.NS_REQ, new Code(facade,"Create a Namespace",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ NsType nst = NsType.fromString(req.getParameter("type"));
+ Result<Void> r = context.requestNS(trans, req, resp,nst);
+
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.CREATED_201);
+ break;
+ case Status.ACC_Future:
+ resp.setStatus(HttpStatus.ACCEPTED_202);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * removes a Namespace from Authz DB
+ *
+ * TESTCASES: TC_NS1, TC_NSdelete1
+ */
+ authzAPI.route(DELETE,"/authz/ns/:ns",API.VOID, new Code(facade,"Delete a Namespace",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.deleteNS(trans, req, resp, pathParam(req,":ns"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * Add an Admin in NS in Authz DB
+ *
+ * TESTCASES: TC_NS1
+ */
+ authzAPI.route(POST,"/authz/ns/:ns/admin/:id",API.VOID, new Code(facade,"Add an Admin to a Namespace",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.addAdminToNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.CREATED_201);
+ break;
+ case Status.ACC_Future:
+ resp.setStatus(HttpStatus.ACCEPTED_202);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * Removes an Admin from Namespace in Authz DB
+ *
+ * TESTCASES: TC_NS1
+ */
+ authzAPI.route(DELETE,"/authz/ns/:ns/admin/:id",API.VOID, new Code(facade,"Remove an Admin from a Namespace",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.delAdminFromNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * Add an Admin in NS in Authz DB
+ *
+ * TESTCASES: TC_NS1
+ */
+ authzAPI.route(POST,"/authz/ns/:ns/responsible/:id",API.VOID, new Code(facade,"Add a Responsible Identity to a Namespace",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.addResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.CREATED_201);
+ break;
+ case Status.ACC_Future:
+ resp.setStatus(HttpStatus.ACCEPTED_202);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+
+ /**
+ *
+ */
+ authzAPI.route(GET,"/authz/nss/:id",API.NSS, new Code(facade,"Return Information about Namespaces", true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getNSsByName(trans, resp, pathParam(req,":id"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * Get all Namespaces where user is an admin
+ */
+ authzAPI.route(GET,"/authz/nss/admin/:user",API.NSS, new Code(facade,"Return Namespaces where User is an Admin", true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getNSsByAdmin(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL)));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * Get all Namespaces where user is a responsible party
+ */
+ authzAPI.route(GET,"/authz/nss/responsible/:user",API.NSS, new Code(facade,"Return Namespaces where User is Responsible", true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getNSsByResponsible(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL)));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * Get all Namespaces where user is an admin or owner
+ */
+ authzAPI.route(GET,"/authz/nss/either/:user",API.NSS, new Code(facade,"Return Namespaces where User Admin or Owner", true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getNSsByEither(trans, resp, pathParam(req,":user"),TRUE.equals(req.getParameter(FULL)));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * Get all children Namespaces
+ */
+ authzAPI.route(GET,"/authz/nss/children/:id",API.NSS, new Code(facade,"Return Child Namespaces", true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getNSsChildren(trans, resp, pathParam(req,":id"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * Set a description of a Namespace
+ */
+ authzAPI.route(PUT,"/authz/ns",API.NS_REQ,new Code(facade,"Set a Description for a Namespace",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.updateNsDescription(trans, req, resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Removes an Owner from Namespace in Authz DB
+ *
+ * TESTCASES: TC_NS1
+ */
+ authzAPI.route(DELETE,"/authz/ns/:ns/responsible/:id",API.VOID, new Code(facade,"Remove a Responsible Identity from Namespace",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.delResponsibilityForNS(trans, resp, pathParam(req,":ns"), pathParam(req,":id"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ authzAPI.route(POST,"/authz/ns/:ns/attrib/:key/:value",API.VOID, new Code(facade,"Add an Attribute from a Namespace",true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.createAttribForNS(trans, resp,
+ pathParam(req,":ns"),
+ pathParam(req,":key"),
+ pathParam(req,":value"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.CREATED_201);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ authzAPI.route(GET,"/authz/ns/attrib/:key",API.KEYS, new Code(facade,"get Ns Key List From Attribute",true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.readNsByAttrib(trans, resp, pathParam(req,":key"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ authzAPI.route(PUT,"/authz/ns/:ns/attrib/:key/:value",API.VOID, new Code(facade,"update an Attribute from a Namespace",true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.updAttribForNS(trans, resp,
+ pathParam(req,":ns"),
+ pathParam(req,":key"),
+ pathParam(req,":value"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ authzAPI.route(DELETE,"/authz/ns/:ns/attrib/:key",API.VOID, new Code(facade,"delete an Attribute from a Namespace",true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.delAttribForNS(trans, resp,
+ pathParam(req,":ns"),
+ pathParam(req,":key"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ }
+
+
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Perms.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Perms.java new file mode 100644 index 00000000..793bba10 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Perms.java @@ -0,0 +1,292 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+import static org.onap.aaf.cssa.rserv.HttpMethods.DELETE;
+import static org.onap.aaf.cssa.rserv.HttpMethods.GET;
+import static org.onap.aaf.cssa.rserv.HttpMethods.POST;
+import static org.onap.aaf.cssa.rserv.HttpMethods.PUT;
+
+import java.net.URLDecoder;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+import org.onap.aaf.cadi.config.Config;
+
+public class API_Perms {
+ public static void timeSensitiveInit(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+ /**
+ * gets all permissions by user name
+ */
+ authzAPI.route(GET, "/authz/perms/user/:user", API.PERMS, new Code(facade,"Get Permissions by User",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getPermsByUser(trans, resp, pathParam(req, "user"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+
+ });
+
+ /**
+ * gets all permissions by user name
+ */
+ authzAPI.route(POST, "/authz/perms/user/:user", API.PERMS, new Code(facade,"Get Permissions by User, Query AAF Perms",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getPermsByUserWithAAFQuery(trans, req, resp, pathParam(req, "user"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+
+ });
+
+
+ } // end timeSensitiveInit
+
+ public static void init(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+ /**
+ * Create a Permission
+ */
+ authzAPI.route(POST,"/authz/perm",API.PERM_REQ,new Code(facade,"Create a Permission",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.createPerm(trans, req, resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.CREATED_201);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * get details of Permission
+ */
+ authzAPI.route(GET, "/authz/perms/:type/:instance/:action", API.PERMS, new Code(facade,"Get Permissions by Key",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getPermsByName(trans, resp,
+ pathParam(req, "type"),
+ URLDecoder.decode(pathParam(req, "instance"),Config.UTF_8),
+ pathParam(req, "action"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+
+ });
+
+ /**
+ * get children of Permission
+ */
+ authzAPI.route(GET, "/authz/perms/:type", API.PERMS, new Code(facade,"Get Permissions by Type",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getPermsByType(trans, resp, pathParam(req, "type"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+
+ });
+
+
+ /**
+ * gets all permissions by role name
+ */
+ authzAPI.route(GET,"/authz/perms/role/:role",API.PERMS,new Code(facade,"Get Permissions by Role",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getPermsForRole(trans, resp, pathParam(req, "role"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * gets all permissions by Namespace
+ */
+ authzAPI.route(GET,"/authz/perms/ns/:ns",API.PERMS,new Code(facade,"Get PermsByNS",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getPermsByNS(trans, resp, pathParam(req, "ns"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Set a perm's description
+ */
+ authzAPI.route(PUT,"/authz/perm",API.PERM_REQ,new Code(facade,"Set Description for Permission",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.updatePermDescription(trans, req, resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Update a permission with a rename
+ */
+ authzAPI.route(PUT,"/authz/perm/:type/:instance/:action",API.PERM_REQ,new Code(facade,"Update a Permission",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.renamePerm(trans, req, resp, pathParam(req, "type"),
+ pathParam(req, "instance"), pathParam(req, "action"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Delete a Permission
+ */
+ authzAPI.route(DELETE,"/authz/perm",API.PERM_REQ,new Code(facade,"Delete a Permission",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.deletePerm(trans,req, resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+
+
+
+ /**
+ * Delete a Permission
+ */
+ authzAPI.route(DELETE,"/authz/perm/:name/:type/:action",API.PERM_KEY,new Code(facade,"Delete a Permission",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.deletePerm(trans, resp,
+ pathParam(req, ":name"),
+ pathParam(req, ":type"),
+ pathParam(req, ":action"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ } // end init
+}
+
+
+
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Roles.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Roles.java new file mode 100644 index 00000000..1669c4ae --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Roles.java @@ -0,0 +1,314 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+import static org.onap.aaf.cssa.rserv.HttpMethods.DELETE;
+import static org.onap.aaf.cssa.rserv.HttpMethods.GET;
+import static org.onap.aaf.cssa.rserv.HttpMethods.POST;
+import static org.onap.aaf.cssa.rserv.HttpMethods.PUT;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+import org.onap.aaf.dao.aaf.cass.Status;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+
+public class API_Roles {
+ public static void init(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+ /**
+ * puts a new role in Authz DB
+ */
+ authzAPI.route(POST,"/authz/role",API.ROLE_REQ, new Code(facade,"Create Role",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.createRole(trans, req, resp);
+
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.CREATED_201);
+ break;
+ case Status.ACC_Future:
+ resp.setStatus(HttpStatus.ACCEPTED_202);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * get Role by name
+ */
+ authzAPI.route(GET, "/authz/roles/:role", API.ROLES, new Code(facade,"GetRolesByFullName",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getRolesByName(trans, resp, pathParam(req, "role"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+
+ });
+
+
+ /**
+ * gets all Roles by user name
+ */
+ authzAPI.route(GET, "/authz/roles/user/:name", API.ROLES, new Code(facade,"GetRolesByUser",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getRolesByUser(trans, resp, pathParam(req, "name"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+
+ });
+
+ /**
+ * gets all Roles by Namespace
+ */
+ authzAPI.route(GET, "/authz/roles/ns/:ns", API.ROLES, new Code(facade,"GetRolesByNS",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getRolesByNS(trans, resp, pathParam(req, "ns"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * gets all Roles by Name without the Namespace
+ */
+ authzAPI.route(GET, "/authz/roles/name/:name", API.ROLES, new Code(facade,"GetRolesByNameOnly",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getRolesByNameOnly(trans, resp, pathParam(req, ":name"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Deletes a Role from Authz DB by Object
+ */
+ authzAPI.route(DELETE,"/authz/role",API.ROLE_REQ, new Code(facade,"Delete Role",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.deleteRole(trans, req, resp);
+
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+
+ }
+ );
+
+
+
+ /**
+ * Deletes a Role from Authz DB by Key
+ */
+ authzAPI.route(DELETE,"/authz/role/:role",API.ROLE, new Code(facade,"Delete Role",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.deleteRole(trans, resp, pathParam(req,":role"));
+
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+
+ }
+ );
+
+
+ /**
+ * Add a Permission to a Role (Grant)
+ */
+ authzAPI.route(POST,"/authz/role/perm",API.ROLE_PERM_REQ, new Code(facade,"Add Permission to Role",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.addPermToRole(trans, req, resp);
+
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.CREATED_201);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ }
+ );
+
+ /**
+ * Get all Roles by Permission
+ */
+ authzAPI.route(GET,"/authz/roles/perm/:type/:instance/:action",API.ROLES,new Code(facade,"GetRolesByPerm",true) {
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.getRolesByPerm(trans, resp,
+ pathParam(req, "type"),
+ pathParam(req, "instance"),
+ pathParam(req, "action"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Set a role's description
+ */
+ authzAPI.route(PUT,"/authz/role",API.ROLE_REQ,new Code(facade,"Set Description for role",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.updateRoleDescription(trans, req, resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Set a permission's roles to roles given
+ */
+ authzAPI.route(PUT,"/authz/role/perm",API.ROLE_PERM_REQ,new Code(facade,"Set a Permission's Roles",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+
+ Result<Void> r = context.resetPermRoles(trans, req, resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Delete a Permission from a Role
+ */
+ authzAPI.route(DELETE,"/authz/role/:role/perm",API.ROLE_PERM_REQ, new Code(facade,"Delete Permission from Role",true) {
+ @Override
+ public void handle(
+ AuthzTrans trans,
+ HttpServletRequest req,
+ HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.delPermFromRole(trans, req, resp);
+
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+
+ }
+ );
+
+ }
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_User.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_User.java new file mode 100644 index 00000000..40f5b8a8 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_User.java @@ -0,0 +1,134 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+import static org.onap.aaf.cssa.rserv.HttpMethods.GET;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+
+/**
+ * User Role APIs
+ *
+ */
+public class API_User {
+ /**
+ * Normal Init level APIs
+ *
+ * @param authzAPI
+ * @param facade
+ * @throws Exception
+ */
+ public static void init(final AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+ /**
+ * get all Users who have Permission X
+ */
+ authzAPI.route(GET,"/authz/users/perm/:type/:instance/:action",API.USERS,new Code(facade,"Get Users By Permission", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+// trans.checkpoint(pathParam(req,"type") + " "
+// + pathParam(req,"instance") + " "
+// + pathParam(req,"action"));
+//
+ Result<Void> r = context.getUsersByPermission(trans, resp,
+ pathParam(req, ":type"),
+ pathParam(req, ":instance"),
+ pathParam(req, ":action"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+
+ /**
+ * get all Users who have Role X
+ */
+ authzAPI.route(GET,"/authz/users/role/:role",API.USERS,new Code(facade,"Get Users By Role", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getUsersByRole(trans, resp, pathParam(req, ":role"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Get User Role if exists
+ * @deprecated
+ */
+ authzAPI.route(GET,"/authz/userRole/:user/:role",API.USERS,new Code(facade,"Get if User is In Role", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getUserInRole(trans, resp, pathParam(req,":user"),pathParam(req,":role"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Get User Role if exists
+ */
+ authzAPI.route(GET,"/authz/users/:user/:role",API.USERS,new Code(facade,"Get if User is In Role", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getUserInRole(trans, resp, pathParam(req,":user"),pathParam(req,":role"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+
+
+ }
+
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_UserRole.java b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_UserRole.java new file mode 100644 index 00000000..81b16fa8 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/api/API_UserRole.java @@ -0,0 +1,182 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.api;
+
+import static org.onap.aaf.authz.layer.Result.OK;
+import static org.onap.aaf.cssa.rserv.HttpMethods.DELETE;
+import static org.onap.aaf.cssa.rserv.HttpMethods.GET;
+import static org.onap.aaf.cssa.rserv.HttpMethods.POST;
+import static org.onap.aaf.cssa.rserv.HttpMethods.PUT;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.facade.AuthzFacade;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.AuthAPI;
+import org.onap.aaf.authz.service.Code;
+import org.onap.aaf.authz.service.mapper.Mapper.API;
+
+import com.att.aft.dme2.internal.jetty.http.HttpStatus;
+
+/**
+ * User Role APIs
+ *
+ */
+public class API_UserRole {
+ /**
+ * Normal Init level APIs
+ *
+ * @param authzAPI
+ * @param facade
+ * @throws Exception
+ */
+ public static void init(final AuthAPI authzAPI, AuthzFacade facade) throws Exception {
+ /**
+ * Request User Role Access
+ */
+ authzAPI.route(POST,"/authz/userRole",API.USER_ROLE_REQ,new Code(facade,"Request User Role Access", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.requestUserRole(trans, req, resp);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.CREATED_201);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+
+ /**
+ * Get UserRoles by Role
+ */
+ authzAPI.route(GET,"/authz/userRoles/role/:role",API.USER_ROLES,new Code(facade,"Get UserRoles by Role", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getUserRolesByRole(trans, resp, pathParam(req,":role"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Get UserRoles by User
+ */
+ authzAPI.route(GET,"/authz/userRoles/user/:user",API.USER_ROLES,new Code(facade,"Get UserRoles by User", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.getUserRolesByUser(trans, resp, pathParam(req,":user"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+
+ /**
+ * Update roles attached to user in path
+ */
+ authzAPI.route(PUT,"/authz/userRole/user",API.USER_ROLE_REQ,new Code(facade,"Update Roles for a user", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.resetRolesForUser(trans, resp, req);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+
+ /**
+ * Update users attached to role in path
+ */
+ authzAPI.route(PUT,"/authz/userRole/role",API.USER_ROLE_REQ,new Code(facade,"Update Users for a role", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.resetUsersForRole(trans, resp, req);
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ /**
+ * Extend Expiration Date (according to Organizational rules)
+ */
+ authzAPI.route(PUT, "/authz/userRole/extend/:user/:role", API.VOID, new Code(facade,"Extend Expiration", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.extendUserRoleExpiration(trans,resp,pathParam(req,":user"),pathParam(req,":role"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+
+ }
+
+ });
+
+
+ /**
+ * Create a new ID/Credential
+ */
+ authzAPI.route(DELETE,"/authz/userRole/:user/:role",API.VOID,new Code(facade,"Delete User Role", true) {
+ @Override
+ public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
+ Result<Void> r = context.deleteUserRole(trans, resp, pathParam(req,":user"),pathParam(req,":role"));
+ switch(r.status) {
+ case OK:
+ resp.setStatus(HttpStatus.OK_200);
+ break;
+ default:
+ context.error(trans,resp,r);
+ }
+ }
+ });
+
+ }
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/mapper/Mapper.java b/authz-service/src/main/java/org/onap/aaf/authz/service/mapper/Mapper.java new file mode 100644 index 00000000..ba3a69ed --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/mapper/Mapper.java @@ -0,0 +1,123 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.mapper;
+
+import java.util.Collection;
+import java.util.List;
+
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.service.MayChange;
+import org.onap.aaf.dao.Bytification;
+import org.onap.aaf.dao.aaf.cass.ApprovalDAO;
+import org.onap.aaf.dao.aaf.cass.CertDAO;
+import org.onap.aaf.dao.aaf.cass.CredDAO;
+import org.onap.aaf.dao.aaf.cass.DelegateDAO;
+import org.onap.aaf.dao.aaf.cass.FutureDAO;
+import org.onap.aaf.dao.aaf.cass.HistoryDAO;
+import org.onap.aaf.dao.aaf.cass.Namespace;
+import org.onap.aaf.dao.aaf.cass.PermDAO;
+import org.onap.aaf.dao.aaf.cass.RoleDAO;
+import org.onap.aaf.dao.aaf.cass.UserRoleDAO;
+
+import org.onap.aaf.rosetta.Marshal;
+
+public interface Mapper<
+ NSS,
+ PERMS,
+ PERMKEY,
+ ROLES,
+ USERS,
+ USERROLES,
+ DELGS,
+ CERTS,
+ KEYS,
+ REQUEST,
+ HISTORY,
+ ERROR,
+ APPROVALS>
+{
+ enum API{NSS,NS_REQ,
+ PERMS,PERM_KEY,PERM_REQ,
+ ROLES,ROLE,ROLE_REQ,ROLE_PERM_REQ,
+ USERS,USER_ROLE_REQ,USER_ROLES,
+ CRED_REQ,CERTS,
+ APPROVALS,
+ DELGS,DELG_REQ,
+ KEYS,
+ HISTORY,
+ ERROR,
+ API,
+ VOID};
+ public Class<?> getClass(API api);
+ public<A> Marshal<A> getMarshal(API api);
+ public<A> A newInstance(API api);
+
+ public Result<PermDAO.Data> permkey(AuthzTrans trans, PERMKEY from);
+ public Result<PermDAO.Data> perm(AuthzTrans trans, REQUEST from);
+ public Result<RoleDAO.Data> role(AuthzTrans trans, REQUEST from);
+ public Result<Namespace> ns(AuthzTrans trans, REQUEST from);
+ public Result<CredDAO.Data> cred(AuthzTrans trans, REQUEST from, boolean requiresPass);
+ public Result<USERS> cred(List<CredDAO.Data> lcred, USERS to);
+ public Result<CERTS> cert(List<CertDAO.Data> lcert, CERTS to);
+ public Result<DelegateDAO.Data> delegate(AuthzTrans trans, REQUEST from);
+ public Result<DELGS> delegate(List<DelegateDAO.Data> lDelg);
+ public Result<APPROVALS> approvals(List<ApprovalDAO.Data> lAppr);
+ public Result<List<ApprovalDAO.Data>> approvals(APPROVALS apprs);
+ public Result<List<PermDAO.Data>> perms(AuthzTrans trans, PERMS perms);
+
+ public Result<UserRoleDAO.Data> userRole(AuthzTrans trans, REQUEST from);
+ public Result<PermDAO.Data> permFromRPRequest(AuthzTrans trans, REQUEST from);
+ public Result<RoleDAO.Data> roleFromRPRequest(AuthzTrans trans, REQUEST from);
+
+ /*
+ * Check Requests of varying sorts for Future fields set
+ */
+ public Result<FutureDAO.Data> future(AuthzTrans trans, String table, REQUEST from, Bytification content, boolean enableApproval, Memo memo, MayChange mc);
+
+ public Result<NSS> nss(AuthzTrans trans, Namespace from, NSS to);
+
+ // Note: Prevalidate if NS given is allowed to be seen before calling
+ public Result<NSS> nss(AuthzTrans trans, Collection<Namespace> from, NSS to);
+// public Result<NSS> ns_attrib(AuthzTrans trans, Set<String> from, NSS to);
+ public Result<PERMS> perms(AuthzTrans trans, List<PermDAO.Data> from, PERMS to, boolean filter);
+ public Result<ROLES> roles(AuthzTrans trans, List<RoleDAO.Data> from, ROLES roles, boolean filter);
+ // Note: Prevalidate if NS given is allowed to be seen before calling
+ public Result<USERS> users(AuthzTrans trans, Collection<UserRoleDAO.Data> from, USERS to);
+ public Result<USERROLES> userRoles(AuthzTrans trans, Collection<UserRoleDAO.Data> from, USERROLES to);
+ public Result<KEYS> keys(Collection<String> from);
+
+ public Result<HISTORY> history(AuthzTrans trans, List<HistoryDAO.Data> history, final int sort);
+
+ public ERROR errorFromMessage(StringBuilder holder, String msgID, String text, String... detail);
+
+ /*
+ * A Memo Creator... Use to avoid creating superfluous Strings until needed.
+ */
+ public static interface Memo {
+ public String get();
+ }
+
+
+
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/mapper/Mapper_2_0.java b/authz-service/src/main/java/org/onap/aaf/authz/service/mapper/Mapper_2_0.java new file mode 100644 index 00000000..180e16b0 --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/mapper/Mapper_2_0.java @@ -0,0 +1,791 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.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 org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.org.Organization;
+import org.onap.aaf.authz.org.Organization.Expiration;
+import org.onap.aaf.authz.service.MayChange;
+import org.onap.aaf.cssa.rserv.Pair;
+import org.onap.aaf.dao.Bytification;
+import org.onap.aaf.dao.aaf.cass.ApprovalDAO;
+import org.onap.aaf.dao.aaf.cass.CertDAO;
+import org.onap.aaf.dao.aaf.cass.CredDAO;
+import org.onap.aaf.dao.aaf.cass.DelegateDAO;
+import org.onap.aaf.dao.aaf.cass.FutureDAO;
+import org.onap.aaf.dao.aaf.cass.HistoryDAO;
+import org.onap.aaf.dao.aaf.cass.Namespace;
+import org.onap.aaf.dao.aaf.cass.NsSplit;
+import org.onap.aaf.dao.aaf.cass.NsType;
+import org.onap.aaf.dao.aaf.cass.PermDAO;
+import org.onap.aaf.dao.aaf.cass.RoleDAO;
+import org.onap.aaf.dao.aaf.cass.Status;
+import org.onap.aaf.dao.aaf.cass.UserRoleDAO;
+import org.onap.aaf.dao.aaf.cass.DelegateDAO.Data;
+import org.onap.aaf.dao.aaf.hl.Question;
+import org.onap.aaf.dao.aaf.hl.Question.Access;
+
+import org.onap.aaf.cadi.aaf.marshal.CertsMarshal;
+import org.onap.aaf.cadi.util.Vars;
+import org.onap.aaf.inno.env.Env;
+import org.onap.aaf.inno.env.TimeTaken;
+import org.onap.aaf.inno.env.util.Chrono;
+import org.onap.aaf.rosetta.Marshal;
+
+import aaf.v2_0.Api;
+import aaf.v2_0.Approval;
+import aaf.v2_0.Approvals;
+import aaf.v2_0.Certs;
+import aaf.v2_0.Certs.Cert;
+import aaf.v2_0.CredRequest;
+import aaf.v2_0.Delg;
+import aaf.v2_0.DelgRequest;
+import aaf.v2_0.Delgs;
+import aaf.v2_0.Error;
+import aaf.v2_0.History;
+import aaf.v2_0.History.Item;
+import aaf.v2_0.Keys;
+import aaf.v2_0.NsRequest;
+import aaf.v2_0.Nss;
+import aaf.v2_0.Nss.Ns;
+import aaf.v2_0.Nss.Ns.Attrib;
+import aaf.v2_0.Perm;
+import aaf.v2_0.PermKey;
+import aaf.v2_0.PermRequest;
+import aaf.v2_0.Perms;
+import aaf.v2_0.Pkey;
+import aaf.v2_0.Request;
+import aaf.v2_0.Role;
+import aaf.v2_0.RolePermRequest;
+import aaf.v2_0.RoleRequest;
+import aaf.v2_0.Roles;
+import aaf.v2_0.UserRole;
+import aaf.v2_0.UserRoleRequest;
+import aaf.v2_0.UserRoles;
+import aaf.v2_0.Users;
+import aaf.v2_0.Users.User;
+
+public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRoles, Delgs, Certs, Keys, Request, History, Error, Approvals> {
+ private Question q;
+
+ public Mapper_2_0(Question q) {
+ this.q = q;
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.service.mapper.Mapper#ns(java.lang.Object, org.onap.aaf.authz.service.mapper.Mapper.Holder)
+ */
+ @Override
+ public Result<Namespace> ns(AuthzTrans trans, Request base) {
+ NsRequest from = (NsRequest)base;
+ Namespace namespace = new Namespace();
+ namespace.name = from.getName();
+ namespace.admin = from.getAdmin();
+ namespace.owner = from.getResponsible();
+ namespace.description = from.getDescription();
+ trans.checkpoint(namespace.name, Env.ALWAYS);
+
+ NsType nt = NsType.fromString(from.getType());
+ if(nt.equals(NsType.UNKNOWN)) {
+ String ns = namespace.name;
+ int count = 0;
+ for(int i=ns.indexOf('.');
+ i>=0;
+ i=ns.indexOf('.',i+1)) {
+ ++count;
+ }
+ switch(count) {
+ case 0: nt = NsType.ROOT;break;
+ case 1: nt = NsType.COMPANY;break;
+ default: nt = NsType.APP;
+ }
+ }
+ namespace.type = nt.type;
+
+ return Result.ok(namespace);
+ }
+
+ @Override
+ public Result<Nss> nss(AuthzTrans trans, Namespace from, Nss to) {
+ List<Ns> nss = to.getNs();
+ Ns ns = new Ns();
+ ns.setName(from.name);
+ if(from.admin!=null)ns.getAdmin().addAll(from.admin);
+ if(from.owner!=null)ns.getResponsible().addAll(from.owner);
+ if(from.attrib!=null) {
+ for(Pair<String,String> attrib : from.attrib) {
+ Attrib toAttrib = new Attrib();
+ toAttrib.setKey(attrib.x);
+ toAttrib.setValue(attrib.y);
+ ns.getAttrib().add(toAttrib);
+ }
+ }
+
+ ns.setDescription(from.description);
+ nss.add(ns);
+ return Result.ok(to);
+ }
+
+ /**
+ * Note: Prevalidate if NS given is allowed to be seen before calling
+ */
+ @Override
+ public Result<Nss> nss(AuthzTrans trans, Collection<Namespace> from, Nss to) {
+ List<Ns> nss = to.getNs();
+ for(Namespace nd : from) {
+ Ns ns = new Ns();
+ ns.setName(nd.name);
+ ns.getAdmin().addAll(nd.admin);
+ ns.getResponsible().addAll(nd.owner);
+ ns.setDescription(nd.description);
+ if(nd.attrib!=null) {
+ for(Pair<String,String> attrib : nd.attrib) {
+ Attrib toAttrib = new Attrib();
+ toAttrib.setKey(attrib.x);
+ toAttrib.setValue(attrib.y);
+ ns.getAttrib().add(toAttrib);
+ }
+ }
+
+ nss.add(ns);
+ }
+ return Result.ok(to);
+ }
+
+ @Override
+ public Result<Perms> perms(AuthzTrans trans, List<PermDAO.Data> from, Perms to, boolean filter) {
+ List<Perm> perms = to.getPerm();
+ TimeTaken tt = trans.start("Filter Perms before return", Env.SUB);
+ try {
+ if(from!=null) {
+ for (PermDAO.Data data : from) {
+ if(!filter || q.mayUser(trans, trans.user(), data, Access.read).isOK()) {
+ Perm perm = new Perm();
+ perm.setType(data.fullType());
+ perm.setInstance(data.instance);
+ perm.setAction(data.action);
+ for(String role : data.roles(false)) {
+ perm.getRoles().add(role);
+ }
+ perm.setDescription(data.description);
+ perms.add(perm);
+ }
+ }
+ }
+ } finally {
+ tt.done();
+ }
+
+ tt = trans.start("Sort Perms", Env.SUB);
+ try {
+ Collections.sort(perms, new Comparator<Perm>() {
+ @Override
+ public int compare(Perm perm1, Perm perm2) {
+ int typeCompare = perm1.getType().compareToIgnoreCase(perm2.getType());
+ if (typeCompare == 0) {
+ int instanceCompare = perm1.getInstance().compareToIgnoreCase(perm2.getInstance());
+ if (instanceCompare == 0) {
+ return perm1.getAction().compareToIgnoreCase(perm2.getAction());
+ }
+ return instanceCompare;
+ }
+ return typeCompare;
+ }
+ });
+ } finally {
+ tt.done();
+ }
+ return Result.ok(to);
+ }
+
+ @Override
+ public Result<List<PermDAO.Data>> perms(AuthzTrans trans, Perms perms) {
+ List<PermDAO.Data> lpd = new ArrayList<PermDAO.Data>();
+ for (Perm p : perms.getPerm()) {
+ Result<NsSplit> nss = q.deriveNsSplit(trans, p.getType());
+ PermDAO.Data pd = new PermDAO.Data();
+ if(nss.isOK()) {
+ pd.ns=nss.value.ns;
+ pd.type = nss.value.name;
+ pd.instance = p.getInstance();
+ pd.action = p.getAction();
+ for (String role : p.getRoles())
+ pd.roles(true).add(role);
+ lpd.add(pd);
+ } else {
+ return Result.err(nss);
+ }
+ }
+ return Result.ok(lpd);
+ }
+
+ @Override
+ public Result<PermDAO.Data> permkey(AuthzTrans trans, Pkey from) {
+ return q.permFrom(trans, from.getType(),from.getInstance(),from.getAction());
+ }
+
+ @Override
+ public Result<PermDAO.Data> permFromRPRequest(AuthzTrans trans, Request req) {
+ RolePermRequest from = (RolePermRequest)req;
+ Pkey perm = from.getPerm();
+ if(perm==null)return Result.err(Status.ERR_NotFound, "Permission not found");
+ Result<NsSplit> nss = q.deriveNsSplit(trans, perm.getType());
+ PermDAO.Data pd = new PermDAO.Data();
+ if(nss.isOK()) {
+ pd.ns=nss.value.ns;
+ pd.type = nss.value.name;
+ pd.instance = from.getPerm().getInstance();
+ pd.action = from.getPerm().getAction();
+ trans.checkpoint(pd.fullPerm(), Env.ALWAYS);
+
+ String[] roles = {};
+
+ if (from.getRole() != null) {
+ roles = from.getRole().split(",");
+ }
+ for (String role : roles) {
+ pd.roles(true).add(role);
+ }
+ return Result.ok(pd);
+ } else {
+ return Result.err(nss);
+ }
+ }
+
+ @Override
+ public Result<RoleDAO.Data> roleFromRPRequest(AuthzTrans trans, Request req) {
+ RolePermRequest from = (RolePermRequest)req;
+ Result<NsSplit> nss = q.deriveNsSplit(trans, from.getRole());
+ RoleDAO.Data rd = new RoleDAO.Data();
+ if(nss.isOK()) {
+ rd.ns = nss.value.ns;
+ rd.name = nss.value.name;
+ trans.checkpoint(rd.fullName(), Env.ALWAYS);
+ return Result.ok(rd);
+ } else {
+ return Result.err(nss);
+ }
+ }
+
+ @Override
+ public Result<PermDAO.Data> perm(AuthzTrans trans, Request req) {
+ PermRequest from = (PermRequest)req;
+ Result<NsSplit> nss = q.deriveNsSplit(trans, from.getType());
+ PermDAO.Data pd = new PermDAO.Data();
+ if(nss.isOK()) {
+ pd.ns=nss.value.ns;
+ pd.type = nss.value.name;
+ pd.instance = from.getInstance();
+ pd.action = from.getAction();
+ pd.description = from.getDescription();
+ trans.checkpoint(pd.fullPerm(), Env.ALWAYS);
+ return Result.ok(pd);
+ } else {
+ return Result.err(nss);
+ }
+ }
+
+ @Override
+ public Result<RoleDAO.Data> role(AuthzTrans trans, Request base) {
+ RoleRequest from = (RoleRequest)base;
+ Result<NsSplit> nss = q.deriveNsSplit(trans, from.getName());
+ if(nss.isOK()) {
+ RoleDAO.Data to = new RoleDAO.Data();
+ to.ns = nss.value.ns;
+ to.name = nss.value.name;
+ to.description = from.getDescription();
+ trans.checkpoint(to.fullName(), Env.ALWAYS);
+
+ return Result.ok(to);
+ } else {
+ return Result.err(nss);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.service.mapper.Mapper#roles(java.util.List)
+ */
+ @Override
+ public Result<Roles> roles(AuthzTrans trans, List<RoleDAO.Data> from, Roles to, boolean filter) {
+ for(RoleDAO.Data frole : from) {
+ // Only Add Data to view if User is allowed to see this Role
+ //if(!filter || q.mayUserViewRole(trans, trans.user(), frole).isOK()) {
+ if(!filter || q.mayUser(trans, trans.user(), frole,Access.read).isOK()) {
+ Role role = new Role();
+ role.setName(frole.ns + '.' + frole.name);
+ role.setDescription(frole.description);
+ for(String p : frole.perms(false)) { // can see any Perms in the Role he has permission for
+ Result<String[]> rpa = PermDAO.Data.decodeToArray(trans,q,p);
+ if(rpa.notOK()) return Result.err(rpa);
+
+ String[] pa = rpa.value;
+ Pkey pKey = new Pkey();
+ pKey.setType(pa[0]+'.'+pa[1]);
+ pKey.setInstance(pa[2]);
+ pKey.setAction(pa[3]);
+ role.getPerms().add(pKey);
+ }
+ to.getRole().add(role);
+ }
+ }
+ return Result.ok(to);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.onap.aaf.authz.service.mapper.Mapper#users(java.util.Collection, java.lang.Object)
+ *
+ * Note: Prevalidate all data for permission to view
+ */
+ @Override
+ public Result<Users> users(AuthzTrans trans, Collection<UserRoleDAO.Data> from, Users to) {
+ List<User> cu = to.getUser();
+ for(UserRoleDAO.Data urd : from) {
+ User user = new User();
+ user.setId(urd.user);
+ user.setExpires(Chrono.timeStamp(urd.expires));
+ cu.add(user);
+ }
+ return Result.ok(to);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.onap.aaf.authz.service.mapper.Mapper#users(java.util.Collection, java.lang.Object)
+ *
+ * Note: Prevalidate all data for permission to view
+ */
+ @Override
+ public Result<UserRoles> userRoles(AuthzTrans trans, Collection<UserRoleDAO.Data> from, UserRoles to) {
+ List<UserRole> cu = to.getUserRole();
+ for(UserRoleDAO.Data urd : from) {
+ UserRole ur = new UserRole();
+ ur.setUser(urd.user);
+ ur.setRole(urd.role);
+ ur.setExpires(Chrono.timeStamp(urd.expires));
+ cu.add(ur);
+ }
+ return Result.ok(to);
+ }
+
+ /**
+ *
+ * @param base
+ * @param start
+ * @return
+ */
+ @Override
+ public Result<UserRoleDAO.Data> userRole(AuthzTrans trans, Request base) {
+ try {
+ UserRoleRequest from = (UserRoleRequest)base;
+
+ // Setup UserRoleData, either for immediate placement, or for future
+ UserRoleDAO.Data to = new UserRoleDAO.Data();
+ if (from.getUser() != null) {
+ String user = from.getUser();
+ to.user = user;
+ }
+ if (from.getRole() != null) {
+ to.role(trans,q,from.getRole());
+ }
+ to.expires = getExpires(trans.org(),Expiration.UserInRole,base,from.getUser());
+ trans.checkpoint(to.toString(), Env.ALWAYS);
+
+ return Result.ok(to);
+ } catch (Exception t) {
+ return Result.err(Status.ERR_BadData,t.getMessage());
+ }
+ }
+
+ @Override
+ public Result<CredDAO.Data> cred(AuthzTrans trans, Request base, boolean requiresPass) {
+ CredRequest from = (CredRequest)base;
+ CredDAO.Data to = new CredDAO.Data();
+ to.id=from.getId();
+ to.ns = Question.domain2ns(to.id);
+ String passwd = from.getPassword();
+ if(requiresPass) {
+ String ok = trans.org().isValidPassword(to.id,passwd);
+ if(ok.length()>0) {
+ return Result.err(Status.ERR_BadData,ok);
+ }
+
+ } else {
+ to.type=0;
+ }
+ if(passwd != null) {
+ to.cred = ByteBuffer.wrap(passwd.getBytes());
+ to.type = CredDAO.RAW;
+ } else {
+ to.type = 0;
+ }
+
+ // Note: Ensure requested EndDate created will match Organization Password Rules
+ // P.S. Do not apply TempPassword rule here. Do that when you know you are doing a Create/Reset (see Service)
+ to.expires = getExpires(trans.org(),Expiration.Password,base,from.getId());
+ trans.checkpoint(to.id, Env.ALWAYS);
+
+ return Result.ok(to);
+ }
+
+ @Override
+ public Result<Users> cred(List<CredDAO.Data> from, Users to) {
+ List<User> cu = to.getUser();
+ for(CredDAO.Data cred : from) {
+ User user = new User();
+ user.setId(cred.id);
+ user.setExpires(Chrono.timeStamp(cred.expires));
+ user.setType(cred.type);
+ cu.add(user);
+ }
+ return Result.ok(to);
+ }
+
+@Override
+ public Result<Certs> cert(List<CertDAO.Data> from, Certs to) {
+ List<Cert> lc = to.getCert();
+ for(CertDAO.Data fcred : from) {
+ Cert cert = new Cert();
+ cert.setId(fcred.id);
+ cert.setX500(fcred.x500);
+ /**TODO - change Interface
+ * @deprecated */
+ cert.setFingerprint(fcred.serial.toByteArray());
+ lc.add(cert);
+ }
+ return Result.ok(to);
+ }
+
+ /**
+ * Analyze whether Requests should be acted on now, or in the future, based on Start Date, and whether the requester
+ * is allowed to change this value directly
+ *
+ * Returning Result.OK means it should be done in the future.
+ * Returning Result.ACC_Now means to act on table change now.
+ */
+ @Override
+ public Result<FutureDAO.Data> future(AuthzTrans trans, String table, Request from,
+ Bytification content, boolean enableApproval, Memo memo, MayChange mc) {
+ Result<?> rMayChange = mc.mayChange();
+ boolean needsAppr;
+ if(needsAppr = rMayChange.notOK()) {
+ if(enableApproval) {
+ if(!trans.futureRequested()) {
+ return Result.err(rMayChange);
+ }
+ } else {
+ return Result.err(rMayChange);
+ }
+ }
+ GregorianCalendar now = new GregorianCalendar();
+ GregorianCalendar start = from.getStart()==null?now:from.getStart().toGregorianCalendar();
+
+ GregorianCalendar expires = trans.org().expiration(start, Expiration.Future);
+ XMLGregorianCalendar xgc;
+ if((xgc=from.getEnd())!=null) {
+ GregorianCalendar fgc = xgc.toGregorianCalendar();
+ expires = expires.before(fgc)?expires:fgc; // Min of desired expiration, and Org expiration
+ }
+
+ //TODO needs two answers from this. What's the NSS, and may Change.
+ FutureDAO.Data fto;
+ if(start.after(now) || needsAppr ) {
+ //String user = trans.user();
+ fto = new FutureDAO.Data();
+ fto.target=table;
+ fto.memo = memo.get();
+ fto.start = start.getTime();
+ fto.expires = expires.getTime();
+ if(needsAppr) { // Need to add Approvers...
+ /*
+ Result<Data> rslt = mc.getNsd();
+ if(rslt.notOKorIsEmpty())return Result.err(rslt);
+ appr.addAll(mc.getNsd().value.responsible);
+ try {
+ //Note from 2013 Is this getting Approvers for user only? What about Delegates?
+ // 3/25/2014. Approvers are set by Corporate policy. We don't have to worry here about what that means.
+ // It is important to get Delegates, if necessary, at notification time
+ // If we add delegates now, it will get all confused as to who is actually responsible.
+ for(Organization.User ou : org.getApprovers(trans, user)) {
+ appr.add(ou.email);
+ }
+ } catch (Exception e) {
+ return Result.err(Status.ERR_Policy,org.getName() + " did not respond with Approvers: " + e.getLocalizedMessage());
+ }
+ */
+ }
+ try {
+ fto.construct = content.bytify();
+ } catch (Exception e) {
+ return Result.err(Status.ERR_BadData,"Data cannot be saved for Future.");
+ }
+ } else {
+ return Result.err(Status.ACC_Now, "Make Data changes now.");
+ }
+ return Result.ok(fto);
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.onap.aaf.authz.service.mapper.Mapper#history(java.util.List)
+ */
+ @Override
+ public Result<History> history(AuthzTrans trans, List<HistoryDAO.Data> history, final int sort) {
+ History hist = new History();
+ List<Item> items = hist.getItem();
+ for(HistoryDAO.Data data : history) {
+ History.Item item = new History.Item();
+ item.setYYYYMM(Integer.toString(data.yr_mon));
+ Date date = Chrono.uuidToDate(data.id);
+ item.setTimestamp(Chrono.timeStamp(date));
+ item.setAction(data.action);
+ item.setMemo(data.memo);
+ item.setSubject(data.subject);
+ item.setTarget(data.target);
+ item.setUser(data.user);
+ items.add(item);
+ }
+
+ if(sort != 0) {
+ TimeTaken tt = trans.start("Sort ", Env.SUB);
+ try {
+ java.util.Collections.sort(items, new Comparator<Item>() {
+ @Override
+ public int compare(Item o1, Item o2) {
+ return sort*(o1.getTimestamp().compare(o2.getTimestamp()));
+ }
+ });
+ } finally {
+ tt.done();
+ }
+ }
+ return Result.ok(hist);
+ }
+
+ @Override
+ public Error errorFromMessage(StringBuilder holder, String msgID, String text, String... var) {
+ Error err = new Error();
+ err.setMessageId(msgID);
+ // AT&T Restful Error Format requires numbers "%" placements
+ err.setText(Vars.convert(holder, text, var));
+ for(String s : var) {
+ err.getVariables().add(s);
+ }
+ return err;
+ }
+
+ @Override
+ public Class<?> getClass(API api) {
+ switch(api) {
+ case NSS: return Nss.class;
+ case NS_REQ: return NsRequest.class;
+ case PERMS: return Perms.class;
+ case PERM_KEY: return PermKey.class;
+ case ROLES: return Roles.class;
+ case ROLE: return Role.class;
+ case USERS: return Users.class;
+ case DELGS: return Delgs.class;
+ case CERTS: return Certs.class;
+ case DELG_REQ: return DelgRequest.class;
+ case PERM_REQ: return PermRequest.class;
+ case ROLE_REQ: return RoleRequest.class;
+ case CRED_REQ: return CredRequest.class;
+ case USER_ROLE_REQ: return UserRoleRequest.class;
+ case USER_ROLES: return UserRoles.class;
+ case ROLE_PERM_REQ: return RolePermRequest.class;
+ case APPROVALS: return Approvals.class;
+ case KEYS: return Keys.class;
+ case HISTORY: return History.class;
+// case MODEL: return Model.class;
+ case ERROR: return Error.class;
+ case API: return Api.class;
+ case VOID: return Void.class;
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <A> A newInstance(API api) {
+ switch(api) {
+ case NS_REQ: return (A) new NsRequest();
+ case NSS: return (A) new Nss();
+ case PERMS: return (A)new Perms();
+ case PERM_KEY: return (A)new PermKey();
+ case ROLES: return (A)new Roles();
+ case ROLE: return (A)new Role();
+ case USERS: return (A)new Users();
+ case DELGS: return (A)new Delgs();
+ case CERTS: return (A)new Certs();
+ case PERM_REQ: return (A)new PermRequest();
+ case CRED_REQ: return (A)new CredRequest();
+ case ROLE_REQ: return (A)new RoleRequest();
+ case USER_ROLE_REQ: return (A)new UserRoleRequest();
+ case USER_ROLES: return (A)new UserRoles();
+ case ROLE_PERM_REQ: return (A)new RolePermRequest();
+ case HISTORY: return (A)new History();
+ case KEYS: return (A)new Keys();
+ //case MODEL: return (A)new Model();
+ case ERROR: return (A)new Error();
+ case API: return (A)new Api();
+ case VOID: return null;
+
+ case APPROVALS: return (A) new Approvals();
+ case DELG_REQ: return (A) new DelgRequest();
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ /**
+ * Get Typed Marshaler as they are defined
+ *
+ * @param api
+ * @return
+ */
+ public <A> Marshal<A> getMarshal(API api) {
+ switch(api) {
+ case CERTS: return (Marshal<A>) new CertsMarshal();
+ default:
+ return null;
+ }
+ }
+
+ @Override
+ public Result<Approvals> approvals(List<ApprovalDAO.Data> lAppr) {
+ Approvals apprs = new Approvals();
+ List<Approval> lappr = apprs.getApprovals();
+ Approval a;
+ for(ApprovalDAO.Data appr : lAppr) {
+ a = new Approval();
+ a.setId(appr.id.toString());
+ a.setTicket(appr.ticket.toString());
+ a.setUser(appr.user);
+ a.setApprover(appr.approver);
+ a.setType(appr.type);
+ a.setStatus(appr.status);
+ a.setMemo(appr.memo);
+ a.setOperation(appr.operation);
+ a.setUpdated(Chrono.timeStamp(appr.updated));
+ lappr.add(a);
+ }
+ return Result.ok(apprs);
+ }
+
+ @Override
+ public Result<List<ApprovalDAO.Data>> approvals(Approvals apprs) {
+ List<ApprovalDAO.Data> lappr = new ArrayList<ApprovalDAO.Data>();
+ for(Approval a : apprs.getApprovals()) {
+ ApprovalDAO.Data ad = new ApprovalDAO.Data();
+ String str = a.getId();
+ if(str!=null)ad.id=UUID.fromString(str);
+ str = a.getTicket();
+ if(str!=null)ad.ticket=UUID.fromString(str);
+ ad.user=a.getUser();
+ ad.approver=a.getApprover();
+ ad.type=a.getType();
+ ad.status=a.getStatus();
+ ad.operation=a.getOperation();
+ ad.memo=a.getMemo();
+
+ XMLGregorianCalendar xgc = a.getUpdated();
+ if(xgc!=null)ad.updated=xgc.toGregorianCalendar().getTime();
+ lappr.add(ad);
+ }
+ return Result.ok(lappr);
+ }
+
+ @Override
+ public Result<Delgs> delegate(List<DelegateDAO.Data> lDelg) {
+ Delgs delgs = new Delgs();
+ List<Delg> ldelg = delgs.getDelgs();
+ Delg d;
+ for(DelegateDAO.Data del: lDelg) {
+ d = new Delg();
+ d.setUser(del.user);
+ d.setDelegate(del.delegate);
+ if(del.expires!=null)d.setExpires(Chrono.timeStamp(del.expires));
+ ldelg.add(d);
+ }
+ return Result.ok(delgs);
+ }
+
+ @Override
+ public Result<Data> delegate(AuthzTrans trans, Request base) {
+ try {
+ DelgRequest from = (DelgRequest)base;
+ DelegateDAO.Data to = new DelegateDAO.Data();
+ String user = from.getUser();
+ to.user = user;
+ String delegate = from.getDelegate();
+ to.delegate = delegate;
+ to.expires = getExpires(trans.org(),Expiration.UserDelegate,base,from.getUser());
+ trans.checkpoint(to.user+"=>"+to.delegate, Env.ALWAYS);
+
+ return Result.ok(to);
+ } catch (Exception t) {
+ return Result.err(Status.ERR_BadData,t.getMessage());
+ }
+ }
+
+ /*
+ * We want "Expired" dates to start at a specified time set by the Organization, and consistent wherever
+ * the date is created from.
+ */
+ private Date getExpires(Organization org, Expiration exp, Request base, String id) {
+ XMLGregorianCalendar end = base.getEnd();
+ GregorianCalendar gc = end==null?new GregorianCalendar():end.toGregorianCalendar();
+ GregorianCalendar orggc;
+ orggc = org.expiration(gc,exp,id);
+
+ // We'll choose the lesser of dates to ensure Policy Compliance...
+
+ GregorianCalendar endgc = end==null||gc.after(orggc)?orggc:gc;
+ // Allow the Organization to determine when official "day Start" begins, Specifically when to consider something Expired.
+ endgc = Chrono.firstMomentOfDay(endgc);
+ endgc.set(GregorianCalendar.HOUR_OF_DAY, org.startOfDay());
+ return endgc.getTime();
+ }
+
+
+ @Override
+ public Result<Keys> keys(Collection<String> from) {
+ Keys keys = new Keys();
+ keys.getKey().addAll(from);
+ return Result.ok(keys).emptyList(from.isEmpty());
+ }
+
+}
diff --git a/authz-service/src/main/java/org/onap/aaf/authz/service/validation/Validator.java b/authz-service/src/main/java/org/onap/aaf/authz/service/validation/Validator.java new file mode 100644 index 00000000..6eca6cef --- /dev/null +++ b/authz-service/src/main/java/org/onap/aaf/authz/service/validation/Validator.java @@ -0,0 +1,386 @@ +/*******************************************************************************
+ * ============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 org.onap.aaf.authz.service.validation;
+
+import java.util.regex.Pattern;
+
+import org.onap.aaf.authz.cadi.DirectAAFLur.PermPermission;
+import org.onap.aaf.authz.env.AuthzTrans;
+import org.onap.aaf.authz.layer.Result;
+import org.onap.aaf.authz.org.Organization;
+import org.onap.aaf.dao.aaf.cass.CredDAO;
+import org.onap.aaf.dao.aaf.cass.DelegateDAO;
+import org.onap.aaf.dao.aaf.cass.Namespace;
+import org.onap.aaf.dao.aaf.cass.PermDAO;
+import org.onap.aaf.dao.aaf.cass.RoleDAO;
+import org.onap.aaf.dao.aaf.cass.UserRoleDAO;
+
+/**
+ * Validator
+ * Consistently apply content rules for content (incoming)
+ *
+ * Note: We restrict content for usability in URLs (because RESTful service), and avoid
+ * issues with Regular Expressions, and other enabling technologies.
+ *
+ */
+public class Validator {
+ // % () ,-. 0-9 =A-Z _a-z
+ private static final String ESSENTIAL="\\x25\\x28\\x29\\x2C-\\x2E\\x30-\\x39\\x3D\\x40-\\x5A\\x5F\\x61-\\x7A";
+ private static final Pattern ESSENTIAL_CHARS=Pattern.compile("["+ESSENTIAL+"]+");
+
+ // Must be 1 or more of Alphanumeric or the following :._-
+ // '*' only allowed when it is the only character, or the only element in a key separator
+ // :* :hello:* :hello:*:there etc
+ public static final Pattern ACTION_CHARS=Pattern.compile(
+ "["+ESSENTIAL+"]+" + // All AlphaNumeric+
+ "|\\*" // Just Star
+ );
+
+ public static final Pattern INST_CHARS=Pattern.compile(
+ "["+ESSENTIAL+"]+[\\*]*" + // All AlphaNumeric+ possibly ending with *
+ "|\\*" + // Just Star
+ "|(([:/]\\*)|([:/][!]{0,1}["+ESSENTIAL+"]+[\\*]*[:/]*))+" // Key :asdf:*:sdf*:sdk
+ );
+
+ // Must be 1 or more of Alphanumeric or the following ._-, and be in the form id@domain
+ public static final Pattern ID_CHARS=Pattern.compile("[\\w.-]+@[\\w.-]+");
+ // Must be 1 or more of Alphanumeric or the following ._-
+ public static final Pattern NAME_CHARS=Pattern.compile("[\\w.-]+");
+
+ private final Pattern actionChars;
+ private final Pattern instChars;
+ private StringBuilder msgs;
+
+ /**
+ * Default Validator does not check for non-standard Action/Inst chars
+ *
+ *
+ * IMPORTANT: Use ONLY when the Validator is doing something simple... NullOrBlank
+ */
+ public Validator() {
+ actionChars = ACTION_CHARS;
+ instChars = INST_CHARS;
+ }
+
+ /**
+ * When Trans is passed in, check for non-standard Action/Inst chars
+ *
+ * This is an opportunity to change characters, if required.
+ *
+ * Use for any Object method passed (i.e. role(RoleDAO.Data d) ), to ensure fewer bugs.
+ *
+ * @param trans
+ */
+ public Validator(AuthzTrans trans) {
+ actionChars = ACTION_CHARS;
+ instChars = INST_CHARS;
+ }
+
+
+ public Validator perm(Result<PermDAO.Data> rpd) {
+ if(rpd.notOK()) {
+ msg(rpd.details);
+ } else {
+ perm(rpd.value);
+ }
+ return this;
+ }
+
+
+ public Validator perm(PermDAO.Data pd) {
+ if(pd==null) {
+ msg("Perm Data is null.");
+ } else {
+ ns(pd.ns);
+ permType(pd.type,pd.ns);
+ permInstance(pd.instance);
+ permAction(pd.action);
+ if(pd.roles!=null) {
+ for(String role : pd.roles) {
+ role(role);
+ }
+ }
+ }
+ return this;
+ }
+
+ public Validator role(Result<RoleDAO.Data> rrd) {
+ if(rrd.notOK()) {
+ msg(rrd.details);
+ } else {
+ role(rrd.value);
+ }
+ return this;
+ }
+
+ public Validator role(RoleDAO.Data pd) {
+ if(pd==null) {
+ msg("Role Data is null.");
+ } else {
+ ns(pd.ns);
+ role(pd.name);
+ if(pd.perms!=null) {
+ for(String perm : pd.perms) {
+ String[] ps = perm.split("\\|");
+ if(ps.length!=3) {
+ msg("Perm [" + perm + "] in Role [" + pd.fullName() + "] is not correctly separated with '|'");
+ } else {
+ permType(ps[0],null);
+ permInstance(ps[1]);
+ permAction(ps[2]);
+ }
+ }
+ }
+ }
+ return this;
+ }
+
+ public Validator delegate(Organization org, Result<DelegateDAO.Data> rdd) {
+ if(rdd.notOK()) {
+ msg(rdd.details);
+ } else {
+ delegate(org, rdd.value);
+ }
+ return this;
+ }
+
+ public Validator delegate(Organization org, DelegateDAO.Data dd) {
+ if(dd==null) {
+ msg("Delegate Data is null.");
+ } else {
+ user(org,dd.user);
+ user(org,dd.delegate);
+ }
+ return this;
+ }
+
+
+ public Validator cred(Organization org, Result<CredDAO.Data> rcd, boolean isNew) {
+ if(rcd.notOK()) {
+ msg(rcd.details);
+ } else {
+ cred(org,rcd.value,isNew);
+ }
+ return this;
+ }
+
+ public Validator cred(Organization org, CredDAO.Data cd, boolean isNew) {
+ if(cd==null) {
+ msg("Cred Data is null.");
+ } else {
+ if(nob(cd.id,ID_CHARS)) {
+ msg("ID [" + cd.id + "] is invalid");
+ }
+ if(!org.isValidCred(cd.id)) {
+ msg("ID [" + cd.id + "] is invalid for a cred");
+ }
+ String str = cd.id;
+ int idx = str.indexOf('@');
+ if(idx>0) {
+ str = str.substring(0,idx);
+ }
+
+ if(cd.id.endsWith(org.getRealm())) {
+ if(isNew && (str=org.isValidID(str)).length()>0) {
+ msg(cd.id,str);
+ }
+ }
+
+ if(cd.type==null) {
+ msg("Credential Type must be set");
+ } else {
+ switch(cd.type) {
+ case CredDAO.BASIC_AUTH_SHA256:
+ // ok
+ break;
+ default:
+ msg("Credential Type [",Integer.toString(cd.type),"] is invalid");
+ }
+ }
+ }
+ return this;
+ }
+
+
+ public Validator user(Organization org, String user) {
+ if(nob(user,ID_CHARS)) {
+ msg("User [",user,"] is invalid.");
+ }
+ //TODO Change when Multi-Org solution is created
+// if(org instanceof ATT) {
+// if(!user.endsWith("@csp.att.com") &&
+// !org.isValidCred(user))
+// msg("User [",user,"] is not valid ID for Credential in ",org.getRealm());
+// }
+ return this;
+ }
+
+ public Validator ns(Result<Namespace> nsd) {
+ notOK(nsd);
+ ns(nsd.value.name);
+ for(String s : nsd.value.admin) {
+ if(nob(s,ID_CHARS)) {
+ msg("Admin [" + s + "] is invalid.");
+ }
+
+ }
+ for(String s : nsd.value.owner) {
+ if(nob(s,ID_CHARS)) {
+ msg("Responsible [" + s + "] is invalid.");
+ }
+
+ }
+ return this;
+ }
+
+
+ public Validator ns(String ns) {
+ if(nob(ns,NAME_CHARS)){
+ msg("NS [" + ns + "] is invalid.");
+ }
+ return this;
+ }
+
+ public String errs() {
+ return msgs.toString();
+ }
+
+
+ public Validator permType(String type, String ns) {
+ // TODO check for correct Splits? Type|Instance|Action ?
+ if(nob(type,NAME_CHARS)) {
+ msg("Perm Type [" + (ns==null?"":ns+(type.length()==0?"":'.'))+type + "] is invalid.");
+ }
+ return this;
+ }
+
+ public Validator permInstance(String instance) {
+ // TODO check for correct Splits? Type|Instance|Action ?
+ if(nob(instance,instChars)) {
+ msg("Perm Instance [" + instance + "] is invalid.");
+ }
+ return this;
+ }
+
+ public Validator permAction(String action) {
+ // TODO check for correct Splits? Type|Instance|Action ?
+ if(nob(action, actionChars)) {
+ msg("Perm Action [" + action + "] is invalid.");
+ }
+ return this;
+ }
+
+ public Validator role(String role) {
+ if(nob(role, NAME_CHARS)) {
+ msg("Role [" + role + "] is invalid.");
+ }
+ return this;
+ }
+
+ public Validator user_role(UserRoleDAO.Data urdd) {
+ if(urdd==null) {
+ msg("UserRole is null");
+ } else {
+ role(urdd.role);
+ nullOrBlank("UserRole.ns",urdd.ns);
+ nullOrBlank("UserRole.rname",urdd.rname);
+ }
+ return this;
+ }
+
+ public Validator nullOrBlank(String name, String str) {
+ if(str==null) {
+ msg(name + " is null.");
+ } else if(str.length()==0) {
+ msg(name + " is blank.");
+ }
+ return this;
+ }
+
+ public Validator nullOrBlank(PermDAO.Data pd) {
+ if(pd==null) {
+ msg("Permission is null");
+ } else {
+ nullOrBlank("NS",pd.ns).
+ nullOrBlank("Type",pd.type).
+ nullOrBlank("Instance",pd.instance).
+ nullOrBlank("Action",pd.action);
+ }
+ return this;
+ }
+
+ public Validator nullOrBlank(RoleDAO.Data rd) {
+ if(rd==null) {
+ msg("Role is null");
+ } else {
+ nullOrBlank("NS",rd.ns).
+ nullOrBlank("Name",rd.name);
+ }
+ return this;
+ }
+
+ // nob = Null Or Not match Pattern
+ private boolean nob(String str, Pattern p) {
+ return str==null || !p.matcher(str).matches();
+ }
+
+ private void msg(String ... strs) {
+ if(msgs==null) {
+ msgs=new StringBuilder();
+ }
+ for(String str : strs) {
+ msgs.append(str);
+ }
+ msgs.append('\n');
+ }
+
+ public boolean err() {
+ return msgs!=null;
+ }
+
+
+ public Validator notOK(Result<?> res) {
+ if(res==null) {
+ msgs.append("Result object is blank");
+ } else if(res.notOK()) {
+ msgs.append(res.getClass().getSimpleName() + " is not OK");
+ }
+ return this;
+ }
+
+ public Validator key(String key) {
+ if(nob(key,NAME_CHARS)) {
+ msg("NS Prop Key [" + key + "] is invalid");
+ }
+ return this;
+ }
+
+ public Validator value(String value) {
+ if(nob(value,ESSENTIAL_CHARS)) {
+ msg("NS Prop value [" + value + "] is invalid");
+ }
+ return this;
+ }
+
+
+}
|