From bd890c575163e4d87ac24198b9c68a39cf4bbc4d Mon Sep 17 00:00:00 2001 From: sg481n Date: Mon, 28 Aug 2017 12:11:35 -0400 Subject: 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 --- authz-service/src/main/assemble/swm.xml | 35 + authz-service/src/main/config/authAPI.props | 24 + authz-service/src/main/config/log4j.properties | 90 + .../src/main/config/lrm-authz-service.xml | 82 + .../java/org/onap/aaf/authz/cadi/DirectAAFLur.java | 170 + .../org/onap/aaf/authz/cadi/DirectAAFUserPass.java | 74 + .../onap/aaf/authz/cadi/DirectCertIdentity.java | 79 + .../org/onap/aaf/authz/facade/AuthzFacade.java | 263 ++ .../onap/aaf/authz/facade/AuthzFacadeFactory.java | 57 + .../org/onap/aaf/authz/facade/AuthzFacadeImpl.java | 2565 +++++++++++++ .../org/onap/aaf/authz/facade/AuthzFacade_2_0.java | 65 + .../java/org/onap/aaf/authz/service/AuthAPI.java | 330 ++ .../aaf/authz/service/AuthzCassServiceImpl.java | 3973 ++++++++++++++++++++ .../org/onap/aaf/authz/service/AuthzService.java | 748 ++++ .../main/java/org/onap/aaf/authz/service/Code.java | 45 + .../java/org/onap/aaf/authz/service/MayChange.java | 33 + .../org/onap/aaf/authz/service/api/API_Api.java | 93 + .../onap/aaf/authz/service/api/API_Approval.java | 108 + .../org/onap/aaf/authz/service/api/API_Creds.java | 278 ++ .../onap/aaf/authz/service/api/API_Delegate.java | 154 + .../onap/aaf/authz/service/api/API_History.java | 239 ++ .../org/onap/aaf/authz/service/api/API_Mgmt.java | 275 ++ .../org/onap/aaf/authz/service/api/API_NS.java | 397 ++ .../org/onap/aaf/authz/service/api/API_Perms.java | 292 ++ .../org/onap/aaf/authz/service/api/API_Roles.java | 314 ++ .../org/onap/aaf/authz/service/api/API_User.java | 134 + .../onap/aaf/authz/service/api/API_UserRole.java | 182 + .../org/onap/aaf/authz/service/mapper/Mapper.java | 123 + .../onap/aaf/authz/service/mapper/Mapper_2_0.java | 791 ++++ .../aaf/authz/service/validation/Validator.java | 386 ++ authz-service/src/main/resources/authAPI.props | 24 + .../src/main/resources/docker-compose/aafcli.sh | 9 + .../main/resources/docker-compose/data/ecomp.cql | 169 + .../resources/docker-compose/data/identities.dat | 7 + .../resources/docker-compose/data/identities.idx | Bin 0 -> 56 bytes .../main/resources/docker-compose/data/init.cql | 242 ++ .../resources/docker-compose/data2/identities.dat | 9 + .../resources/docker-compose/docker-compose.yml | 58 + .../resources/docker-compose/old/dme2-3.1.200.jar | Bin 0 -> 21798449 bytes .../src/main/resources/docker-compose/runaafcli.sh | 9 + .../main/resources/docker-compose/startupaaf.sh | 32 + .../src/main/resources/docker-compose/sysctl.conf | 3 + .../resources/docker-compose/wait_for_host_port.sh | 17 + authz-service/src/main/sample/authAPI.props | 30 + authz-service/src/main/sample/log4j.properties | 85 + authz-service/src/main/swm/common/deinstall.sh | 40 + authz-service/src/main/swm/common/install.sh | 252 ++ .../src/main/swm/deinstall/postproc/post_proc | 7 + .../src/main/swm/deinstall/preproc/pre_proc | 3 + authz-service/src/main/swm/descriptor.xml | 51 + .../src/main/swm/fallback/postproc/post_proc | 6 + .../src/main/swm/fallback/preproc/pre_proc | 6 + .../src/main/swm/initinst/postproc/post_proc | 6 + .../src/main/swm/initinst/preproc/pre_proc | 7 + .../src/main/swm/install/postproc/post_proc | 7 + .../src/main/swm/install/preproc/pre_proc | 7 + authz-service/src/main/swm/packageNotes.txt | 32 + .../org/onap/aaf/authz/cadi/JU_DirectAAFLur.java | 66 + .../onap/aaf/authz/cadi/JU_DirectAAFUserPass.java | 74 + .../onap/aaf/authz/cadi/JU_DirectCertIdentity.java | 72 + .../org/onap/aaf/authz/service/JU_AuthAPI.java | 75 + .../org/onap/aaf/authz/service/api/JU_API_Api.java | 59 + .../aaf/authz/service/api/JU_API_Approval.java | 61 + .../onap/aaf/authz/service/api/JU_API_Creds.java | 73 + .../aaf/authz/service/api/JU_API_Delegate.java | 55 + .../onap/aaf/authz/service/api/JU_API_History.java | 61 + .../onap/aaf/authz/service/api/JU_API_Mgmt.java | 58 + .../org/onap/aaf/authz/service/api/JU_API_NS.java | 50 + .../onap/aaf/authz/service/api/JU_API_Perms.java | 67 + .../onap/aaf/authz/service/api/JU_API_Roles.java | 56 + .../onap/aaf/authz/service/api/JU_API_User.java | 56 + .../aaf/authz/service/api/JU_API_UserRole.java | 52 + .../aaf/authz/service/mapper/JU_Mapper_2_0.java | 163 + .../onap/aaf/authz/service/test/JU_Validator.java | 159 + .../aaf/authz/service/validation/JU_Validator.java | 175 + 75 files changed, 14949 insertions(+) create mode 100644 authz-service/src/main/assemble/swm.xml create mode 100644 authz-service/src/main/config/authAPI.props create mode 100644 authz-service/src/main/config/log4j.properties create mode 100644 authz-service/src/main/config/lrm-authz-service.xml create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/cadi/DirectAAFLur.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/cadi/DirectAAFUserPass.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/cadi/DirectCertIdentity.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacade.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacadeFactory.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacadeImpl.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/facade/AuthzFacade_2_0.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/AuthAPI.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/AuthzCassServiceImpl.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/AuthzService.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/Code.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/MayChange.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Api.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Approval.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Creds.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Delegate.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_History.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Mgmt.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_NS.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Perms.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_Roles.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_User.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/api/API_UserRole.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/mapper/Mapper.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/mapper/Mapper_2_0.java create mode 100644 authz-service/src/main/java/org/onap/aaf/authz/service/validation/Validator.java create mode 100644 authz-service/src/main/resources/authAPI.props create mode 100644 authz-service/src/main/resources/docker-compose/aafcli.sh create mode 100644 authz-service/src/main/resources/docker-compose/data/ecomp.cql create mode 100644 authz-service/src/main/resources/docker-compose/data/identities.dat create mode 100644 authz-service/src/main/resources/docker-compose/data/identities.idx create mode 100644 authz-service/src/main/resources/docker-compose/data/init.cql create mode 100644 authz-service/src/main/resources/docker-compose/data2/identities.dat create mode 100644 authz-service/src/main/resources/docker-compose/docker-compose.yml create mode 100644 authz-service/src/main/resources/docker-compose/old/dme2-3.1.200.jar create mode 100644 authz-service/src/main/resources/docker-compose/runaafcli.sh create mode 100644 authz-service/src/main/resources/docker-compose/startupaaf.sh create mode 100644 authz-service/src/main/resources/docker-compose/sysctl.conf create mode 100644 authz-service/src/main/resources/docker-compose/wait_for_host_port.sh create mode 100644 authz-service/src/main/sample/authAPI.props create mode 100644 authz-service/src/main/sample/log4j.properties create mode 100644 authz-service/src/main/swm/common/deinstall.sh create mode 100644 authz-service/src/main/swm/common/install.sh create mode 100644 authz-service/src/main/swm/deinstall/postproc/post_proc create mode 100644 authz-service/src/main/swm/deinstall/preproc/pre_proc create mode 100644 authz-service/src/main/swm/descriptor.xml create mode 100644 authz-service/src/main/swm/fallback/postproc/post_proc create mode 100644 authz-service/src/main/swm/fallback/preproc/pre_proc create mode 100644 authz-service/src/main/swm/initinst/postproc/post_proc create mode 100644 authz-service/src/main/swm/initinst/preproc/pre_proc create mode 100644 authz-service/src/main/swm/install/postproc/post_proc create mode 100644 authz-service/src/main/swm/install/preproc/pre_proc create mode 100644 authz-service/src/main/swm/packageNotes.txt create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/cadi/JU_DirectAAFLur.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/cadi/JU_DirectAAFUserPass.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/cadi/JU_DirectCertIdentity.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/JU_AuthAPI.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_Api.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_Approval.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_Creds.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_Delegate.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_History.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_Mgmt.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_NS.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_Perms.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_Roles.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_User.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/api/JU_API_UserRole.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/mapper/JU_Mapper_2_0.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/test/JU_Validator.java create mode 100644 authz-service/src/test/java/org/onap/aaf/authz/service/validation/JU_Validator.java (limited to 'authz-service/src') diff --git a/authz-service/src/main/assemble/swm.xml b/authz-service/src/main/assemble/swm.xml new file mode 100644 index 00000000..561d7b4b --- /dev/null +++ b/authz-service/src/main/assemble/swm.xml @@ -0,0 +1,35 @@ + + + swm + + zip + + + ${artifactId} + + + target/swm + + + diff --git a/authz-service/src/main/config/authAPI.props b/authz-service/src/main/config/authAPI.props new file mode 100644 index 00000000..6bc78699 --- /dev/null +++ b/authz-service/src/main/config/authAPI.props @@ -0,0 +1,24 @@ +## +## AUTHZ API (authz-service) Properties +## + +hostname=_HOSTNAME_ + +## DISCOVERY (DME2) Parameters on the Command Line +AFT_LATITUDE=_AFT_LATITUDE_ +AFT_LONGITUDE=_AFT_LONGITUDE_ +AFT_ENVIRONMENT=_AFT_ENVIRONMENT_ +DEPLOYED_VERSION=_ARTIFACT_VERSION_ + +## Pull in common/security properties + +cadi_prop_files=_COMMON_DIR_/com.att.aaf.common.props;_COMMON_DIR_/com.att.aaf.props + +##DME2 related parameters + +DMEServiceName=service=com.att.authz.AuthorizationService/version=_MAJOR_VER_._MINOR_VER_._PATCH_VER_/envContext=_ENV_CONTEXT_/routeOffer=_ROUTE_OFFER_ +AFT_DME2_PORT_RANGE=_AUTHZ_SERVICE_PORT_RANGE_ + + +CACHE_HIGH_COUNT=20000 +CACHE_CLEAN_INTERVAL=60000 \ No newline at end of file diff --git a/authz-service/src/main/config/log4j.properties b/authz-service/src/main/config/log4j.properties new file mode 100644 index 00000000..75507e7a --- /dev/null +++ b/authz-service/src/main/config/log4j.properties @@ -0,0 +1,90 @@ +#------------------------------------------------------------------------------- +# ============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. +# * +#------------------------------------------------------------------------------- +############################################################################### +# Copyright (c) 2016 AT&T Intellectual Property. All rights reserved. +############################################################################### +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# +log4j.appender.INIT=org.apache.log4j.DailyRollingFileAppender +log4j.appender.INIT.File=_LOG_DIR_/${LOG4J_FILENAME_init} +log4j.appender.INIT.DatePattern='.'yyyy-MM-dd +#log4j.appender.INIT.MaxFileSize=_MAX_LOG_FILE_SIZE_ +#log4j.appender.INIT.MaxBackupIndex=_MAX_LOG_FILE_BACKUP_COUNT_ +log4j.appender.INIT.layout=org.apache.log4j.PatternLayout +log4j.appender.INIT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSSZ} %m %n + + +log4j.appender.SRVR=org.apache.log4j.DailyRollingFileAppender +log4j.appender.SRVR.File=logs/${LOG4J_FILENAME_authz} +log4j.appender.SRVR.DatePattern='.'yyyy-MM-dd +#log4j.appender.SRVR.MaxFileSize=_MAX_LOG_FILE_SIZE_ +#log4j.appender.SRVR.MaxBackupIndex=_MAX_LOG_FILE_BACKUP_COUNT_ +log4j.appender.SRVR.layout=org.apache.log4j.PatternLayout +log4j.appender.SRVR.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSSZ} %p [%c] %m %n + +log4j.appender.AUDIT=org.apache.log4j.DailyRollingFileAppender +log4j.appender.AUDIT.File=_LOG_DIR_/${LOG4J_FILENAME_audit} +log4j.appender.AUDIT.DatePattern='.'yyyy-MM-dd +#log4j.appender.AUDIT.MaxFileSize=_MAX_LOG_FILE_SIZE_ +#log4j.appender.AUDIT.MaxBackupIndex=_MAX_LOG_FILE_BACKUP_COUNT_ +log4j.appender.AUDIT.layout=org.apache.log4j.PatternLayout +log4j.appender.AUDIT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSSZ} %m %n + +log4j.appender.TRACE=org.apache.log4j.DailyRollingFileAppender +log4j.appender.TRACE.File=logs/${LOG4J_FILENAME_trace} +log4j.appender.TRACE.DatePattern='.'yyyy-MM-dd +#log4j.appender.TRACE.MaxFileSize=_MAX_LOG_FILE_SIZE_ +#log4j.appender.TRACE.MaxBackupIndex=_MAX_LOG_FILE_BACKUP_COUNT_ +log4j.appender.TRACE.layout=org.apache.log4j.PatternLayout +log4j.appender.TRACE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSSZ} %m %n + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] %m %n + +# General Apache libraries +log4j.rootLogger=WARN +log4j.logger.org.apache=WARN,INIT +log4j.logger.dme2=WARN,INIT +log4j.logger.init=INFO,INIT +log4j.logger.authz=_LOG4J_LEVEL_,SRVR +log4j.logger.audit=INFO,AUDIT +log4j.logger.trace=TRACE,TRACE + + diff --git a/authz-service/src/main/config/lrm-authz-service.xml b/authz-service/src/main/config/lrm-authz-service.xml new file mode 100644 index 00000000..ef14fbdf --- /dev/null +++ b/authz-service/src/main/config/lrm-authz-service.xml @@ -0,0 +1,82 @@ + + + + + + com.att.authz._ARTIFACT_ID_ + + _MAJOR_VER_ + _MINOR_VER_ + _PATCH_VER_ + + _ROUTE_OFFER_ + + Java + com.att.authz.service.AuthzAPI + + process.workdir + _ROOT_DIR_ + + + jvm.version + 1.8 + + + jvm.args + -DAFT_LATITUDE=_AFT_LATITUDE_ -DAFT_LONGITUDE=_AFT_LONGITUDE_ -DAFT_ENVIRONMENT=_AFT_ENVIRONMENT_ -Dplatform=_SCLD_PLATFORM_ -Dcom.sun.jndi.ldap.connect.pool.maxsize=20 -Dcom.sun.jndi.ldap.connect.pool.prefsize=10 -Dcom.sun.jndi.ldap.connect.pool.timeout=3000 + + + jvm.classpath + _ROOT_DIR_/etc:_ROOT_DIR_/lib/*: + + + jvm.heap.min + 1024m + + + jvm.heap.max + 2048m + + + start.class + com.att.authz.service.AuthAPI + + + stdout.redirect + _ROOT_DIR_/logs/SystemOut.log + + + stderr.redirect + _ROOT_DIR_/logs/SystemErr.log + + aft + AUTO + 2 + _RESOURCE_MIN_COUNT_ + _RESOURCE_MAX_COUNT_ + _RESOURCE_REGISTRATION_ + com.att.authz:_ARTIFACT_ID_ + _ARTIFACT_VERSION_ + + 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> pdr = question.getPermsByUser(trans, bait.getName(),false); + switch(pdr.status) { + case OK: + for(PermDAO.Data d : pdr.value) { + if(new PermPermission(d).match(pond)) return true; + } + break; + default: + trans.error().log("Can't access Cassandra to fulfill Permission Query: ",pdr.status,"-",pdr.details); + } + return false; + } + + @Override + public void fishAll(Principal bait, List permissions) { + Result> pdr = question.getPermsByUser(env.newTrans(), bait.getName(),false); + switch(pdr.status) { + case OK: + for(PermDAO.Data d : pdr.value) { + permissions.add(new PermPermission(d)); + } + break; + default: + env.error().log("Can't access Cassandra to fulfill Permission Query: ",pdr.status,"-", pdr.details); + } + } + + @Override + public void destroy() { + } + + @Override + public boolean handlesExclusively(Permission pond) { + return false; + } + + /** + * Small Class implementing CADI's Permission with Cassandra Data + * + */ + public static class PermPermission implements Permission { + private PermDAO.Data data; + + public PermPermission(PermDAO.Data d) { + data = d; + } + + public PermPermission(AuthzTrans trans, Question q, String p) { + data = PermDAO.Data.create(trans, q, p); + } + + public PermPermission(String ns, String type, String instance, String action) { + data = new PermDAO.Data(); + data.ns = ns; + data.type = type; + data.instance = instance; + data.action = action; + } + + @Override + public String getKey() { + return data.type; + } + + @Override + public boolean match(Permission p) { + if(p==null)return false; + PermDAO.Data pd; + if(p instanceof DirectAAFLur.PermPermission) { + pd = ((DirectAAFLur.PermPermission)p).data; + if(data.ns.equals(pd.ns)) + if(data.type.equals(pd.type)) + if(data.instance!=null && (data.instance.equals(pd.instance) || "*".equals(data.instance))) + if(data.action!=null && (data.action.equals(pd.action) || "*".equals(data.action))) + return true; + } else{ + String[] lp = p.getKey().split("\\|"); + if(lp.length<3)return false; + if(data.fullType().equals(lp[0])) + if(data.instance!=null && (data.instance.equals(lp[1]) || "*".equals(data.instance))) + if(data.action!=null && (data.action.equals(lp[2]) || "*".equals(data.action))) + return true; + } + return false; + } + + @Override + public String permType() { + return "AAFLUR"; + } + + } + + public String toString() { + return "DirectAAFLur is enabled"; + + } + + @Override + public boolean supports(String userName) { + //TODO + return true; + } + + @Override + public Permission createPerm(String p) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void clear(Principal p, StringBuilder report) { + // TODO Auto-generated method stub + + } +} diff --git a/authz-service/src/main/java/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 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> 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 requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type); + + public abstract Result getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns); + + public abstract Result getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); + + public abstract Result getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); + + public abstract Result getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full); + + public abstract Result getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String pathParam); + + public abstract Result addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + + public abstract Result delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + + public abstract Result addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + + public abstract Result delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id); + + public abstract Result updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns); + + // NS Attribs + public abstract Result createAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value); + + public abstract Result readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key); + + public abstract Result updAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key, String value); + + public abstract Result delAttribForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String key); + + /* + * Permissions + */ + public abstract Result createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result getPermsByName(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action); + + public abstract Result getPermsByUser(AuthzTrans trans, HttpServletResponse response, String user); + + public abstract Result getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest request, HttpServletResponse response, String user); + + public abstract Result getPermsByType(AuthzTrans trans, HttpServletResponse resp, String type); + + public abstract Result getPermsForRole(AuthzTrans trans, HttpServletResponse response, String roleName); + + public abstract Result getPermsByNS(AuthzTrans trans, HttpServletResponse response, String ns); + + public abstract Result renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, + String type, String instance, String action); + + public abstract Result updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result deletePerm(AuthzTrans trans, HttpServletResponse resp, + String perm, String type, String action); + + /* + * Roles + */ + public abstract Result createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse response); + + public abstract Result getRolesByName(AuthzTrans trans,HttpServletResponse resp, String name); + + public abstract Result getRolesByNS(AuthzTrans trans, HttpServletResponse resp, String ns); + + public abstract Result getRolesByNameOnly(AuthzTrans trans, HttpServletResponse resp, String nameOnly); + + public abstract Result getRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user); + + public abstract Result getRolesByPerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action); + + public abstract Result updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result addPermToRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); + + public abstract Result delPermFromRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); + + public abstract Result deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result deleteRole(AuthzTrans trans, HttpServletResponse resp, String role); + + /* + * Users + */ + + public abstract Result getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role); + + public abstract Result getUsersByPermission(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action); + + + + /* + * Delegates + */ + public abstract Result createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result deleteDelegate(AuthzTrans trans, String user); + + public abstract Result getDelegatesByUser(AuthzTrans trans, String userName, HttpServletResponse resp); + + public abstract Result getDelegatesByDelegate(AuthzTrans trans, String userName, HttpServletResponse resp); + + /* + * Credentials + */ + public abstract Result createUserCred(AuthzTrans trans, HttpServletRequest req); + + public abstract Result changeUserCred(AuthzTrans trans, HttpServletRequest req); + + public abstract Result extendUserCred(AuthzTrans trans, HttpServletRequest req, String days); + + public abstract Result getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns); + + public abstract Result getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id); + + public abstract Result deleteUserCred(AuthzTrans trans, HttpServletRequest req); + + public abstract Result validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth); + + public abstract Result doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + /* + * Miscellaneous + */ + /** + * Place Standard Messages based on HTTP Code onto Error Data Structure, and write to OutputStream + * Log message + */ + public abstract void error(AuthzTrans trans, HttpServletResponse response, Result result); + + /* + * UserRole + */ + public abstract Result requestUserRole(AuthzTrans trans,HttpServletRequest req, HttpServletResponse resp); + + public abstract Result getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role); + + public abstract Result getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role); + + public abstract Result getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user); + + public abstract Result deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role); + + public abstract Result resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req); + + public abstract Result resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req); + + public abstract Result extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, + String role); + + /* + * Approval + */ + public abstract Result updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp); + + public abstract Result getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user); + + public abstract Result getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket); + + public abstract Result getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver); + + + /* + * History + */ + public abstract Result getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort); + + public abstract Result getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); + + public abstract Result getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); + + public abstract Result getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String subject, int[] yyyymm, final int sort); + + /* + * Cache + */ + public abstract Result cacheClear(AuthzTrans trans, String pathParam); + + public abstract Result cacheClear(AuthzTrans trans, String string,String segments); + + public abstract void dbReset(AuthzTrans trans); + + + + /* + * API + */ + public Result getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet); + + public abstract Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String typeCode, boolean optional); + + public abstract Result getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id); + + + + + +} diff --git a/authz-service/src/main/java/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 extends FacadeImpl implements AuthzFacade + { + private static final String FORBIDDEN = "Forbidden"; + private static final String NOT_FOUND = "Not Found"; + private static final String NOT_ACCEPTABLE = "Not Acceptable"; + private static final String GENERAL_SERVICE_ERROR = "General Service Error"; + private static final String NO_DATA = "***No Data***"; + private AuthzService service = null; + private final RosettaDF nssDF; + private final RosettaDF permsDF; + private final RosettaDF roleDF; + private final RosettaDF usersDF; + private final RosettaDF userrolesDF; + private final RosettaDF certsDF; + private final RosettaDF delgDF; + private final RosettaDF permRequestDF; + private final RosettaDF roleRequestDF; + private final RosettaDF userRoleRequestDF; + private final RosettaDF rolePermRequestDF; + private final RosettaDF nsRequestDF; + private final RosettaDF credRequestDF; + private final RosettaDF delgRequestDF; + private final RosettaDF historyDF; + private final RosettaDF keysDF; + + private final RosettaDF errDF; + private final RosettaDF approvalDF; + // Note: Api is not different per Version + private final RosettaDF apiDF; + + + @SuppressWarnings("unchecked") + public AuthzFacadeImpl(AuthzEnv env, AuthzService service, Data.TYPE dataType) throws APIException { + this.service = service; + (nssDF = env.newDataFactory(service.mapper().getClass(API.NSS))).in(dataType).out(dataType); + (permRequestDF = env.newDataFactory(service.mapper().getClass(API.PERM_REQ))).in(dataType).out(dataType); + (permsDF = env.newDataFactory(service.mapper().getClass(API.PERMS))).in(dataType).out(dataType); +// (permKeyDF = env.newDataFactory(service.mapper().getClass(API.PERM_KEY))).in(dataType).out(dataType); + (roleDF = env.newDataFactory(service.mapper().getClass(API.ROLES))).in(dataType).out(dataType); + (roleRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_REQ))).in(dataType).out(dataType); + (usersDF = env.newDataFactory(service.mapper().getClass(API.USERS))).in(dataType).out(dataType); + (userrolesDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLES))).in(dataType).out(dataType); + (certsDF = env.newDataFactory(service.mapper().getClass(API.CERTS))).in(dataType).out(dataType) + .rootMarshal((Marshal) service.mapper().getMarshal(API.CERTS)); + ; + (userRoleRequestDF = env.newDataFactory(service.mapper().getClass(API.USER_ROLE_REQ))).in(dataType).out(dataType); + (rolePermRequestDF = env.newDataFactory(service.mapper().getClass(API.ROLE_PERM_REQ))).in(dataType).out(dataType); + (nsRequestDF = env.newDataFactory(service.mapper().getClass(API.NS_REQ))).in(dataType).out(dataType); + (credRequestDF = env.newDataFactory(service.mapper().getClass(API.CRED_REQ))).in(dataType).out(dataType); + (delgRequestDF = env.newDataFactory(service.mapper().getClass(API.DELG_REQ))).in(dataType).out(dataType); + (historyDF = env.newDataFactory(service.mapper().getClass(API.HISTORY))).in(dataType).out(dataType); + ( keysDF = env.newDataFactory(service.mapper().getClass(API.KEYS))).in(dataType).out(dataType); + (delgDF = env.newDataFactory(service.mapper().getClass(API.DELGS))).in(dataType).out(dataType); + (approvalDF = env.newDataFactory(service.mapper().getClass(API.APPROVALS))).in(dataType).out(dataType); + (errDF = env.newDataFactory(service.mapper().getClass(API.ERROR))).in(dataType).out(dataType); + (apiDF = env.newDataFactory(Api.class)).in(dataType).out(dataType); + } + + public Mapper mapper() { + return service.mapper(); + } + + /* (non-Javadoc) + * @see 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 requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type) { + TimeTaken tt = trans.start(CREATE_NS, Env.SUB|Env.ALWAYS); + try { + REQUEST request; + try { + Data rd = nsRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,rd.asString()); + } + request = rd.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_NS); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.createNS(trans,request,type); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,CREATE_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#addAdminToNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result addAdminToNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(ADD_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result rp = service.addAdminNS(trans,ns,id); + switch(rp.status) { + case OK: + //TODO Perms?? + setContentType(resp,nsRequestDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,ADD_NS_ADMIN); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#delAdminFromNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result delAdminFromNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(DELETE_NS_ADMIN + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result rp = service.delAdminNS(trans, ns, id); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_NS_ADMIN); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#addAdminToNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result addResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(ADD_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result rp = service.addResponsibleNS(trans,ns,id); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,ADD_NS_RESPONSIBLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#delAdminFromNS(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.String) + */ + @Override + public Result delResponsibilityForNS(AuthzTrans trans, HttpServletResponse resp, String ns, String id) { + TimeTaken tt = trans.start(DELETE_NS_RESPONSIBLE + ' ' + ns + ' ' + id, Env.SUB|Env.ALWAYS); + try { + Result rp = service.delResponsibleNS(trans, ns, id); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_NS_RESPONSIBLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getNSsByName(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getNSsByName(AuthzTrans trans, HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(GET_NS_BY_NAME + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getNSbyName(trans, ns); + switch(rp.status) { + case OK: + RosettaData data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_NAME); + return Result.err(e); + } finally { + tt.done(); + } + } + +// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getNSsByAdmin(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getNSsByAdmin(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ + TimeTaken tt = trans.start(GET_NS_BY_ADMIN + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getNSbyAdmin(trans, user, full); + switch(rp.status) { + case OK: + RosettaData data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_ADMIN); + return Result.err(e); + } finally { + tt.done(); + } + } + +// TODO: uncomment when on cassandra 2.1.2 for MyNamespace GUI page + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getNSsByResponsible(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ + TimeTaken tt = trans.start(GET_NS_BY_RESPONSIBLE + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getNSbyResponsible(trans, user, full); + switch(rp.status) { + case OK: + RosettaData data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_RESPONSIBLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getNSsByEither(AuthzTrans trans, HttpServletResponse resp, String user, boolean full){ + TimeTaken tt = trans.start(GET_NS_BY_EITHER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getNSbyEither(trans, user, full); + + switch(rp.status) { + case OK: + RosettaData data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_BY_EITHER); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getNSsByResponsible(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getNSsChildren(AuthzTrans trans, HttpServletResponse resp, String parent){ + TimeTaken tt = trans.start(GET_NS_CHILDREN + ' ' + parent, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getNSsChildren(trans, parent); + switch(rp.status) { + case OK: + RosettaData data = nssDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,nssDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_NS_CHILDREN); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result updateNsDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_NS_DESC, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = nsRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,UPDATE_NS_DESC); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.updateNsDescription(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_NS_DESC); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#requestNS(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result deleteNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(DELETE_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result rp = service.deleteNS(trans,ns); + switch(rp.status) { + case OK: + setContentType(resp,nsRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + private final static String NS_CREATE_ATTRIB = "nsCreateAttrib"; + private final static String NS_UPDATE_ATTRIB = "nsUpdateAttrib"; + private final static String READ_NS_BY_ATTRIB = "readNsByAttrib"; + private final static String NS_DELETE_ATTRIB = "nsDeleteAttrib"; + + /* (non-Javadoc) + * @see 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 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 readNsByAttrib(AuthzTrans trans, HttpServletResponse resp, String key) { + TimeTaken tt = trans.start(READ_NS_BY_ATTRIB + ' ' + key, Env.SUB|Env.ALWAYS); + try { + Result rp = service.readNsByAttrib(trans, key); + switch(rp.status) { + case OK: + RosettaData data = keysDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,keysDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,READ_NS_BY_ATTRIB); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see 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 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 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 createPerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start( CREATE_PERMISSION, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_PERMISSION); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.createPerm(trans,rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,CREATE_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getChildPerms(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getPermsByType(AuthzTrans trans, HttpServletResponse resp, String perm) { + TimeTaken tt = trans.start(GET_PERMS_BY_TYPE + ' ' + perm, Env.SUB|Env.ALWAYS); + try { + + Result rp = service.getPermsByType(trans, perm); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMS_BY_TYPE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getPermsByName(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action) { + + TimeTaken tt = trans.start(GET_PERMS_BY_NAME + ' ' + type + + '|' + instance + '|' + action, Env.SUB|Env.ALWAYS); + try { + + Result rp = service.getPermsByName(trans, type, instance, action); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMS_BY_TYPE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getPermsByUser(AuthzTrans trans, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getPermsByUser(trans, user); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_USER, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getPermissionByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getPermsByUserWithAAFQuery(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_USER_WITH_QUERY + ' ' + user, Env.SUB|Env.ALWAYS); + try { + PERMS perms; + try { + RosettaData data = permsDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + perms = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_PERMISSION); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.getPermsByUser(trans, perms, user); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_USER_WITH_QUERY , user); + return Result.err(e); + } finally { + tt.done(); + } + } + + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getPermissionsForRole(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getPermsForRole(AuthzTrans trans, HttpServletResponse resp, String roleName) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_ROLE + ' ' + roleName, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getPermsByRole(trans, roleName); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getPermsByNS(AuthzTrans trans,HttpServletResponse resp,String ns) { + TimeTaken tt = trans.start(GET_PERMISSIONS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getPermsByNS(trans, ns); + switch(rp.status) { + case OK: + RosettaData data = permsDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_PERMISSIONS_BY_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see 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 renamePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, + String origType, String origInstance, String origAction) { + String cmdDescription = UPDATE_PERMISSION; + TimeTaken tt = trans.start( cmdDescription + ' ' + origType + ' ' + origInstance + ' ' + origAction, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,cmdDescription); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.renamePerm(trans,rreq, origType, origInstance, origAction); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,cmdDescription); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result updatePermDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_PERM_DESC, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,UPDATE_PERM_DESC); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.updatePermDescription(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_PERM_DESC); + return Result.err(e); + } finally { + tt.done(); + } + } + + + @Override + public Result resetPermRoles(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(SET_PERMISSION_ROLES_TO, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN, SET_PERMISSION_ROLES_TO); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.resetPermRoles(trans, rreq); + + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,SET_PERMISSION_ROLES_TO); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deletePerm(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_PERMISSION, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = permRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,DELETE_PERMISSION); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + + Result rp = service.deletePerm(trans,rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deletePerm(AuthzTrans trans, HttpServletResponse resp, String type, String instance, String action) { + TimeTaken tt = trans.start(DELETE_PERMISSION + type + ' ' + instance + ' ' + action, Env.SUB|Env.ALWAYS); + try { + Result rp = service.deletePerm(trans,type,instance,action); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + public static final String CREATE_ROLE = "createRole"; + public static final String GET_ROLES_BY_USER = "getRolesByUser"; + public static final String GET_ROLES_BY_NS = "getRolesByNS"; + public static final String GET_ROLES_BY_NAME_ONLY = "getRolesByNameOnly"; + public static final String GET_ROLES_BY_NAME = "getRolesByName"; + public static final String GET_ROLES_BY_PERM = "getRolesByPerm"; + public static final String UPDATE_ROLE_DESC = "updateRoleDescription"; + public static final String ADD_PERM_TO_ROLE = "addPermissionToRole"; + public static final String DELETE_PERM_FROM_ROLE = "deletePermissionFromRole"; + public static final String UPDATE_MGTPERM_ROLE = "updateMgtPermRole"; + public static final String DELETE_ROLE = "deleteRole"; + public static final String GET_CERT_BY_ID = "getCertByID"; + + @Override + public Result createRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(CREATE_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = roleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.createRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,roleRequestDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,CREATE_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getRolesByName(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getRolesByName(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(GET_ROLES_BY_NAME + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getRolesByName(trans, role); + switch(rp.status) { + case OK: + RosettaData data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,roleDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_NAME); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getRolesByUser(AuthzTrans trans,HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_ROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getRolesByUser(trans, user); + switch(rp.status) { + case OK: + RosettaData data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,roleDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_USER, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getRolesByNS(AuthzTrans trans,HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(GET_ROLES_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getRolesByNS(trans, ns); + switch(rp.status) { + case OK: + if(!rp.isEmpty()) { + RosettaData data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + } else { + Question.logEncryptTrace(trans, NO_DATA); + } + setContentType(resp,roleDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getRolesByNameOnly(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getRolesByNameOnly(AuthzTrans trans,HttpServletResponse resp, String nameOnly) { + TimeTaken tt = trans.start(GET_ROLES_BY_NAME_ONLY + ' ' + nameOnly, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getRolesByNameOnly(trans, nameOnly); + switch(rp.status) { + case OK: + if(!rp.isEmpty()) { + RosettaData data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + } else { + Question.logEncryptTrace(trans, NO_DATA); + } + setContentType(resp,roleDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_NAME_ONLY); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getRolesByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getRolesByPerm(AuthzTrans trans,HttpServletResponse resp, String type, String instance, String action) { + TimeTaken tt = trans.start(GET_ROLES_BY_PERM + type +' '+instance+' '+action, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getRolesByPerm(trans, type,instance,action); + switch(rp.status) { + case OK: + RosettaData data = roleDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,roleDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_ROLES_BY_PERM); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* + * (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#updateDescription(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result updateRoleDescription(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_ROLE_DESC, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = roleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,UPDATE_ROLE_DESC); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.updateRoleDescription(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,roleRequestDF.getOutType()); + return Result.ok(); + default: + return rp; + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_ROLE_DESC); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result addPermToRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(ADD_PERM_TO_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,ADD_PERM_TO_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.addPermToRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,ADD_PERM_TO_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result delPermFromRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_PERM_FROM_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = rolePermRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,DELETE_PERM_FROM_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + + } + Result rp = service.delPermFromRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + resp.getOutputStream().println(); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_PERM_FROM_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteRole(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(DELETE_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result rp = service.deleteRole(trans, role); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = roleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN,CREATE_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.deleteRole(trans, rreq); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + public static final String CREATE_CRED = "createUserCred"; + private static final String GET_CREDS_BY_NS = "getCredsByNS"; + private static final String GET_CREDS_BY_ID = "getCredsByID"; + public static final String UPDATE_CRED = "updateUserCred"; + public static final String EXTEND_CRED = "extendUserCred"; + public static final String DELETE_CRED = "deleteUserCred"; + public static final String DOES_CRED_MATCH = "doesCredMatch"; + public static final String VALIDATE_BASIC_AUTH = "validateBasicAuth"; + + + + @Override + /** + * Create Credential + * + */ + public Result createUserCred(AuthzTrans trans, HttpServletRequest req) { + TimeTaken tt = trans.start(CREATE_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + return service.createUserCred(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,CREATE_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result changeUserCred(AuthzTrans trans, HttpServletRequest req) { + TimeTaken tt = trans.start(UPDATE_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.changeUserCred(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#extendUserCred(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, int) + */ + @Override + public Result extendUserCred(AuthzTrans trans, HttpServletRequest req, String days) { + TimeTaken tt = trans.start(EXTEND_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.extendUserCred(trans, data.asObject(), days); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,EXTEND_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getCredsByNS(AuthzTrans trans, HttpServletResponse resp, String ns) { + TimeTaken tt = trans.start(GET_CREDS_BY_NS + ' ' + ns, Env.SUB|Env.ALWAYS); + + try { + Result ru = service.getCredsByNS(trans,ns); + switch(ru.status) { + case OK: + RosettaData data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans,trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_CREDS_BY_NS); + return Result.err(e); + } finally { + tt.done(); + } + + } + + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getCredsByID(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getCredsByID(AuthzTrans trans, HttpServletResponse resp, String id) { + TimeTaken tt = trans.start(GET_CREDS_BY_ID + ' ' + id, Env.SUB|Env.ALWAYS); + + try { + Result ru = service.getCredsByID(trans,id); + switch(ru.status) { + case OK: + RosettaData data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_CREDS_BY_ID); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result deleteUserCred(AuthzTrans trans, HttpServletRequest req) { + TimeTaken tt = trans.start(DELETE_CRED, Env.SUB|Env.ALWAYS); + try { + RosettaData data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.deleteUserCred(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (Exception e) { + trans.error().log(e,IN,DELETE_CRED); + return Result.err(e); + } finally { + tt.done(); + } + } + + + @Override + public Result doesCredentialMatch(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DOES_CRED_MATCH, Env.SUB|Env.ALWAYS); + try { + RosettaData data = credRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.doesCredentialMatch(trans, data.asObject()); + } catch(APIException e) { + trans.error().log(e,"Bad Input data"); + return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); + } catch (IOException e) { + trans.error().log(e,IN,DOES_CRED_MATCH); + return Result.err(e); + } finally { + tt.done(); + } + } + + + @Override + public Result validBasicAuth(AuthzTrans trans, HttpServletResponse resp, String basicAuth) { + TimeTaken tt = trans.start(VALIDATE_BASIC_AUTH, Env.SUB|Env.ALWAYS); + try { + Result result = service.validateBasicAuth(trans,basicAuth); + switch(result.status){ + case OK: + resp.getOutputStream().write(Chrono.utcStamp(result.value).getBytes()); + return Result.ok(); + } + return Result.err(result); + } catch (Exception e) { + trans.error().log(e,IN,VALIDATE_BASIC_AUTH); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see 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 getCertInfoByID(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, String id) { + TimeTaken tt = trans.start(GET_CERT_BY_ID, Env.SUB|Env.ALWAYS); + try { + Result rci = service.getCertInfoByID(trans,req,id); + + switch(rci.status) { + case OK: + if(Question.willSpecialLog(trans, trans.user())) { + RosettaData data = certsDF.newData(trans).load(rci.value); + Question.logEncryptTrace(trans,data.asString()); + data.to(resp.getOutputStream()); + } else { + certsDF.direct(trans, rci.value, resp.getOutputStream()); + } + setContentType(resp,certsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rci); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_CERT_BY_ID); + return Result.err(e); + } finally { + tt.done(); + } + } + + public static final String CREATE_DELEGATE = "createDelegate"; + public static final String UPDATE_DELEGATE = "updateDelegate"; + public static final String DELETE_DELEGATE = "deleteDelegate"; + public static final String GET_DELEGATE_USER = "getDelegatesByUser"; + public static final String GET_DELEGATE_DELG = "getDelegatesByDelegate"; + + @Override + public Result createDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(CREATE_DELEGATE, Env.SUB|Env.ALWAYS); + try { + Data data = delgRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.createDelegate(trans, data.asObject()); + } catch (Exception e) { + trans.error().log(e,IN,CREATE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result updateDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_DELEGATE, Env.SUB|Env.ALWAYS); + try { + Data data = delgRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.updateDelegate(trans, data.asObject()); + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteDelegate(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(DELETE_DELEGATE, Env.SUB|Env.ALWAYS); + try { + Data data = delgRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + return service.deleteDelegate(trans, data.asObject()); + } catch (Exception e) { + trans.error().log(e,IN,DELETE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteDelegate(AuthzTrans trans, String userName) { + TimeTaken tt = trans.start(DELETE_DELEGATE + ' ' + userName, Env.SUB|Env.ALWAYS); + try { + return service.deleteDelegate(trans, userName); + } catch (Exception e) { + trans.error().log(e,IN,DELETE_DELEGATE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getDelegatesByUser(AuthzTrans trans, String user, HttpServletResponse resp) { + TimeTaken tt = trans.start(GET_DELEGATE_USER, Env.SUB|Env.ALWAYS); + try { + Result rd = service.getDelegatesByUser(trans, user); + + switch(rd.status) { + case OK: + RosettaData data = delgDF.newData(trans).load(rd.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,delgDF.getOutType()); + return Result.ok(); + default: + return Result.err(rd); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_DELEGATE_USER); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getDelegatesByDelegate(AuthzTrans trans, String delegate, HttpServletResponse resp) { + TimeTaken tt = trans.start(GET_DELEGATE_DELG, Env.SUB|Env.ALWAYS); + try { + Result rd = service.getDelegatesByDelegate(trans, delegate); + switch(rd.status) { + case OK: + RosettaData data = delgDF.newData(trans).load(rd.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + setContentType(resp,delgDF.getOutType()); + return Result.ok(); + default: + return Result.err(rd); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_DELEGATE_DELG); + return Result.err(e); + } finally { + tt.done(); + } + } + + private static final String REQUEST_USER_ROLE = "createUserRole"; + private static final String GET_USERROLES = "getUserRoles"; + private static final String GET_USERROLES_BY_ROLE = "getUserRolesByRole"; + private static final String GET_USERROLES_BY_USER = "getUserRolesByUser"; + private static final String SET_ROLES_FOR_USER = "setRolesForUser"; + private static final String SET_USERS_FOR_ROLE = "setUsersForRole"; + private static final String EXTEND_USER_ROLE = "extendUserRole"; + private static final String DELETE_USER_ROLE = "deleteUserRole"; + @Override + public Result requestUserRole(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(REQUEST_USER_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST request; + try { + Data data = userRoleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + request = data.asObject(); + } catch(APIException e) { + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.createUserRole(trans,request); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,REQUEST_USER_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getUserInRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) { + TimeTaken tt = trans.start(GET_USERROLES + ' ' + user + '|' + role, Env.SUB|Env.ALWAYS); + try { + Result ru = service.getUserInRole(trans,user,role); + switch(ru.status) { + case OK: + RosettaData data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERROLES); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result getUserRolesByUser(AuthzTrans trans, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_USERROLES_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result ru = service.getUserRolesByUser(trans,user); + switch(ru.status) { + case OK: + RosettaData data = userrolesDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERROLES_BY_USER); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result getUserRolesByRole(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(GET_USERROLES_BY_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result ru = service.getUserRolesByRole(trans,role); + switch(ru.status) { + case OK: + RosettaData data = userrolesDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERROLES_BY_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + + } + + + @Override + public Result resetUsersForRole(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) { + TimeTaken tt = trans.start(SET_USERS_FOR_ROLE, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = userRoleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN, SET_USERS_FOR_ROLE); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.resetUsersForRole(trans, rreq); + + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,SET_USERS_FOR_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + + } + + @Override + public Result resetRolesForUser(AuthzTrans trans, HttpServletResponse resp, HttpServletRequest req) { + TimeTaken tt = trans.start(SET_ROLES_FOR_USER, Env.SUB|Env.ALWAYS); + try { + REQUEST rreq; + try { + RosettaData data = userRoleRequestDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + rreq = data.asObject(); + } catch(APIException e) { + trans.error().log("Invalid Input",IN, SET_ROLES_FOR_USER); + return Result.err(Status.ERR_BadData,"Invalid Input"); + } + + Result rp = service.resetRolesForUser(trans, rreq); + + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,SET_ROLES_FOR_USER); + return Result.err(e); + } finally { + tt.done(); + } + + } + + /* (non-Javadoc) + * @see 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 extendUserRoleExpiration(AuthzTrans trans, HttpServletResponse resp, String user, String role) { + TimeTaken tt = trans.start(EXTEND_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS); + try { + return service.extendUserRole(trans,user,role); + } catch (Exception e) { + trans.error().log(e,IN,EXTEND_USER_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result deleteUserRole(AuthzTrans trans, HttpServletResponse resp, String user, String role) { + TimeTaken tt = trans.start(DELETE_USER_ROLE + ' ' + user + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result rp = service.deleteUserRole(trans,user,role); + switch(rp.status) { + case OK: + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,DELETE_USER_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + private static final String UPDATE_APPROVAL = "updateApproval"; + private static final String GET_APPROVALS_BY_USER = "getApprovalsByUser."; + private static final String GET_APPROVALS_BY_TICKET = "getApprovalsByTicket."; + private static final String GET_APPROVALS_BY_APPROVER = "getApprovalsByApprover."; + + @Override + public Result updateApproval(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) { + TimeTaken tt = trans.start(UPDATE_APPROVAL, Env.SUB|Env.ALWAYS); + try { + Data data = approvalDF.newData().load(req.getInputStream()); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + Result rp = service.updateApproval(trans, data.asObject()); + + switch(rp.status) { + case OK: + setContentType(resp,approvalDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,UPDATE_APPROVAL); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getApprovalsByUser(AuthzTrans trans, HttpServletResponse resp, String user) { + TimeTaken tt = trans.start(GET_APPROVALS_BY_USER + ' ' + user, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getApprovalsByUser(trans, user); + switch(rp.status) { + case OK: + RosettaData data = approvalDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + data.to(resp.getOutputStream()); + + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_APPROVALS_BY_USER, user); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getApprovalsByApprover(AuthzTrans trans, HttpServletResponse resp, String approver) { + TimeTaken tt = trans.start(GET_APPROVALS_BY_APPROVER + ' ' + approver, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getApprovalsByApprover(trans, approver); + switch(rp.status) { + case OK: + RosettaData data = approvalDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_APPROVALS_BY_APPROVER,approver); + return Result.err(e); + } finally { + tt.done(); + } + } + + @Override + public Result getApprovalsByTicket(AuthzTrans trans, HttpServletResponse resp, String ticket) { + TimeTaken tt = trans.start(GET_APPROVALS_BY_TICKET, Env.SUB|Env.ALWAYS); + try { + Result rp = service.getApprovalsByTicket(trans, ticket); + switch(rp.status) { + case OK: + RosettaData data = approvalDF.newData(trans).load(rp.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,permsDF.getOutType()); + return Result.ok(); + default: + return Result.err(rp); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_APPROVALS_BY_TICKET); + return Result.err(e); + } finally { + tt.done(); + } + } + + + + public static final String GET_USERS_PERMISSION = "getUsersByPermission"; + public static final String GET_USERS_ROLE = "getUsersByRole"; + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getUsersByRole(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getUsersByRole(AuthzTrans trans, HttpServletResponse resp, String role) { + TimeTaken tt = trans.start(GET_USERS_ROLE + ' ' + role, Env.SUB|Env.ALWAYS); + try { + Result ru = service.getUsersByRole(trans,role); + switch(ru.status) { + case OK: + RosettaData data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERS_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see 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 getUsersByPermission(AuthzTrans trans, HttpServletResponse resp, + String type, String instance, String action) { + TimeTaken tt = trans.start(GET_USERS_PERMISSION + ' ' + type + ' ' + instance + ' ' +action, Env.SUB|Env.ALWAYS); + try { + Result ru = service.getUsersByPermission(trans,type,instance,action); + switch(ru.status) { + case OK: + RosettaData data = usersDF.newData(trans).load(ru.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,usersDF.getOutType()); + return Result.ok(); + default: + return Result.err(ru); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_USERS_PERMISSION); + return Result.err(e); + } finally { + tt.done(); + } + } + + + public static final String GET_HISTORY_USER = "getHistoryByUser"; + public static final String GET_HISTORY_ROLE = "getHistoryByRole"; + public static final String GET_HISTORY_PERM = "getHistoryByPerm"; + public static final String GET_HISTORY_NS = "getHistoryByNS"; + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getHistoryByUser(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public Result getHistoryByUser(AuthzTrans trans, HttpServletResponse resp, String user, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_USER); + sb.append(' '); + sb.append(user); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + + try { + Result rh = service.getHistoryByUser(trans,user,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_USER); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getHistoryByRole(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) + */ + @Override + public Result getHistoryByRole(AuthzTrans trans, HttpServletResponse resp, String role, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_ROLE); + sb.append(' '); + sb.append(role); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + try { + Result rh = service.getHistoryByRole(trans,role,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_ROLE); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getHistoryByNS(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) + */ + @Override + public Result getHistoryByNS(AuthzTrans trans, HttpServletResponse resp, String ns, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_NS); + sb.append(' '); + sb.append(ns); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + try { + Result rh = service.getHistoryByNS(trans,ns,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_NS); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getHistoryByPerm(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, int[]) + */ + @Override + public Result getHistoryByPerm(AuthzTrans trans, HttpServletResponse resp, String perm, int[] yyyymm, final int sort) { + StringBuilder sb = new StringBuilder(); + sb.append(GET_HISTORY_PERM); + sb.append(' '); + sb.append(perm); + sb.append(" for "); + boolean first = true; + for(int i : yyyymm) { + if(first) { + first = false; + } else { + sb.append(','); + } + sb.append(i); + } + TimeTaken tt = trans.start(sb.toString(), Env.SUB|Env.ALWAYS); + try { + Result rh = service.getHistoryByPerm(trans,perm,yyyymm,sort); + switch(rh.status) { + case OK: + RosettaData data = historyDF.newData(trans).load(rh.value); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,historyDF.getOutType()); + return Result.ok(); + default: + return Result.err(rh); + } + } catch (Exception e) { + trans.error().log(e,IN,GET_HISTORY_PERM); + return Result.err(e); + } finally { + tt.done(); + } + } + + public final static String CACHE_CLEAR = "cacheClear "; +// public final static String CACHE_VALIDATE = "validateCache"; + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#cacheClear(org.onap.aaf.authz.env.AuthzTrans, java.lang.String) + */ + @Override + public Result cacheClear(AuthzTrans trans, String cname) { + TimeTaken tt = trans.start(CACHE_CLEAR + cname, Env.SUB|Env.ALWAYS); + try { + return service.cacheClear(trans,cname); + } catch (Exception e) { + trans.error().log(e,IN,CACHE_CLEAR); + return Result.err(e); + } finally { + tt.done(); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#cacheClear(org.onap.aaf.authz.env.AuthzTrans, java.lang.String, java.lang.Integer) + */ + @Override + public Result cacheClear(AuthzTrans trans, String cname, String segments) { + TimeTaken tt = trans.start(CACHE_CLEAR + cname + ", segments[" + segments + ']', Env.SUB|Env.ALWAYS); + try { + String[] segs = segments.split("\\s*,\\s*"); + int isegs[] = new int[segs.length]; + for(int i=0;i getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet rservlet) { + TimeTaken tt = trans.start(API_REPORT, Env.SUB); + try { + Api api = new Api(); + Api.Route ar; + Method[] meths = AuthzCassServiceImpl.class.getDeclaredMethods(); + for(RouteReport rr : rservlet.routeReport()) { + api.getRoute().add(ar = new Api.Route()); + ar.setMeth(rr.meth.name()); + ar.setPath(rr.path); + ar.setDesc(rr.desc); + ar.getContentType().addAll(rr.contextTypes); + for(Method m : meths) { + ApiDoc ad; + if((ad = m.getAnnotation(ApiDoc.class))!=null && + rr.meth.equals(ad.method()) && + rr.path.equals(ad.path())) { + for(String param : ad.params()) { + ar.getParam().add(param); + } + for(String text : ad.text()) { + ar.getComments().add(text); + } + ar.setExpected(ad.expectedCode()); + for(int ec : ad.errorCodes()) { + ar.getExplicitErr().add(ec); + } + } + } + } + RosettaData data = apiDF.newData(trans).load(api); + if(Question.willSpecialLog(trans, trans.user())) { + Question.logEncryptTrace(trans,data.asString()); + } + + data.to(resp.getOutputStream()); + setContentType(resp,apiDF.getOutType()); + return Result.ok(); + + } catch (Exception e) { + trans.error().log(e,IN,API_REPORT); + return Result.err(e); + } finally { + tt.done(); + } + } + + + public final static String API_EXAMPLE = "apiExample"; + + /* (non-Javadoc) + * @see org.onap.aaf.authz.facade.AuthzFacade#getAPIExample(org.onap.aaf.authz.env.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String) + */ + @Override + public Result getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) { + TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB); + try { + String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional); + resp.getOutputStream().print(content); + setContentType(resp,content.contains(" +{ + public AuthzFacade_2_0(AuthzEnv env, + AuthzService service, + Data.TYPE type) throws APIException { + super(env, service, type); + } +} diff --git a/authz-service/src/main/java/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 slist = new ArrayList(); + svcHolder = new DME2ServiceHolder(); + String serviceName = env.getProperty("DMEServiceName",null); + if(serviceName!=null) { + svcHolder.setServiceURI(serviceName); + svcHolder.setManager(dme2); + svcHolder.setContext("/"); + DME2ServletHolder srvHolder = new DME2ServletHolder(this, new String[]{"/authz","/authn","/mgmt"}); + srvHolder.setContextPath("/*"); + slist.add(srvHolder); + + EnumSet edlist = EnumSet.of( + RequestDispatcherType.REQUEST, + RequestDispatcherType.FORWARD, + RequestDispatcherType.ASYNC + ); + + List flist = new ArrayList(); + + // Add DME2 Metrics + // DME2 removed the Metrics Filter in 2.8.8.5 + // flist.add(new DME2FilterHolder(new DME2MetricsFilter(serviceName),"/*",edlist)); + + // Note: Need CADI to fill out User for AuthTransFilter... so it's first + // Make sure there is no AAF TAF configured for Filters + env.setProperty(Config.AAF_URL,null); + + flist.add( + new DME2FilterHolder( + new AuthzTransFilter(env, null /* no connection to AAF... it is AAF */, + new AAFTrustChecker((Env)env), + new DirectAAFLur(env,question), // Note, this will be assigned by AuthzTransFilter to TrustChecker + new BasicHttpTaf(env, directAAFUserPass, + DOMAIN,Long.parseLong(env.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)), + false + ) // Add specialty Direct TAF + ), + "/*", edlist)); + + svcHolder.setFilters(flist); + svcHolder.setServletHolders(slist); + + DME2Server dme2svr = dme2.getServer(); + + String hostname = env.getProperty("HOSTNAME",null); + if(hostname!=null) { + //dme2svr.setHostname(hostname); + hostname=null; + } + // dme2svr.setGracefulShutdownTimeMs(5000); + + env.init().log("Starting AAF Jetty/DME2 server..."); + dme2svr.start(); + try { +// if(env.getProperty("NO_REGISTER",null)!=null) + dme2.bindService(svcHolder); + //env.init().log("DME2 is available as HTTPS on port:",dme2svr.getPort()); + + // Start CacheInfo Listener + HMangr hman = new HMangr(env, new DME2Locator(env, dme2,"https://DME2RESOLVE/"+serviceName,true /*remove self from cache*/)); + SecuritySetter ss; + +// InetAddress ip = InetAddress.getByName(dme2svr.getHostname()); + SecurityInfoC si = new SecurityInfoC(env); + String mechID; + if((mechID=env.getProperty(Config.AAF_MECHID))==null) { + String alias = env.getProperty(Config.CADI_ALIAS); + if(alias==null) { + env.init().log(Config.CADI_ALIAS, "is required for AAF Authentication by Certificate. Alternately, set",Config.AAF_MECHID,"and",Config.AAF_MECHPASS); + System.exit(1); + } + ss = new HX509SS(alias,si,true); + env.init().log("X509 Certificate Client configured:", alias); + } else { + String pass = env.getProperty(Config.AAF_MECHPASS); + if(pass==null) { + env.init().log(Config.AAF_MECHPASS, "is required for AAF Authentication by ID/Pass"); + System.exit(1); + } + ss = new HBasicAuthSS(mechID,env.decrypt(pass, true),si,true); + env.init().log("BasicAuth (ID/Pass) Client configured."); + } + + //TODO Reenable Cache Update + //CacheInfoDAO.startUpdate(env, hman, ss, dme2svr.getHostname(), dme2svr.getPort()); + + while(true) { // Per DME2 Examples... + Thread.sleep(5000); + } + } catch(DME2Exception e) { // Error binding service doesn't seem to stop DME2 or Process + env.init().log(e,"DME2 Initialization Error"); + dme2svr.stop(); + System.exit(1); + } catch(InterruptedException e) { + env.init().log("AAF Jetty Server interrupted!"); + } + } else { + env.init().log("Properties must contain 'DMEServiceName'"); + } + } + + public static void main(String[] args) { + setup(AuthAPI.class,"authAPI.props"); + } +} diff --git a/authz-service/src/main/java/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 + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + */ +public class AuthzCassServiceImpl + implements AuthzService { + + private Mapper mapper; + @Override + public Mapper mapper() {return mapper;} + + private static final String ASTERIX = "*"; + private static final String CACHE = "cache"; + + private final Question ques; + private final Function func; + + public AuthzCassServiceImpl(AuthzTrans trans, Mapper mapper,Question question) { + this.ques = question; + func = new Function(trans, question); + this.mapper = mapper; + + } + +/*********************************** + * NAMESPACE + ***********************************/ + /** + * createNS + * @throws DAOException + * @see 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: ", + "
  • name - What you want to call this Namespace
  • ", + "
  • responsible(s) - Person(s) who receive Notifications and approves Requests ", + "regarding this Namespace. Companies have Policies as to who may take on ", + "this Responsibility. Separate multiple identities with commas
  • ", + "
  • admin(s) - Person(s) who are allowed to make changes on the namespace, ", + "including creating Roles, Permissions and Credentials. Separate multiple ", + "identities with commas
", + "Note: Namespaces are dot-delimited (i.e. com.myCompany.myApp) and must be ", + "created with parent credentials (i.e. To create com.myCompany.myApp, you must ", + "be an admin of com.myCompany or com" + } + ) + @Override + public Result createNS(final AuthzTrans trans, REQUEST from, NsType type) { + final Result rnamespace = mapper.ns(trans, from); + final Validator v = new Validator(); + if(v.ns(rnamespace).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final Namespace namespace = rnamespace.value; + final Result parentNs = ques.deriveNs(trans,namespace.name); + if(parentNs.notOK()) { + return Result.err(parentNs); + } + + if(namespace.name.lastIndexOf('.')<0) { // Root Namespace... Function will check if allowed + return func.createNS(trans, namespace, false); + } + + Result fd = mapper.future(trans, NsDAO.TABLE,from,namespace,true, + new Mapper.Memo() { + @Override + public String get() { + return "Create Namespace [" + namespace.name + ']'; + } + }, + new MayChange() { + private Result rnd; + @Override + public Result mayChange() { + if(rnd==null) { + rnd = ques.mayUser(trans, trans.user(), parentNs.value,Access.write); + } + return rnd; + } + }); + switch(fd.status) { + case OK: + Result> rfc = func.createFuture(trans, fd.value, namespace.name, trans.user(),parentNs.value, "C"); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "NS [%s] is saved for future processing",namespace.name); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.createNS(trans, namespace, false); + default: + return Result.err(fd); + } + } + + @ApiDoc( + method = POST, + path = "/authz/ns/:ns/admin/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 201, + errorCodes = { 403,404,406,409 }, + text = { "Add an Identity :id to the list of Admins for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" } + ) + @Override + public Result addAdminNS(AuthzTrans trans, String ns, String id) { + return func.addUserRole(trans, id, ns,Question.ADMIN); + } + + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns/admin/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Remove an Identity :id from the list of Admins for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" } + ) + @Override + public Result delAdminNS(AuthzTrans trans, String ns, String id) { + return func.delAdmin(trans,ns,id); + } + + @ApiDoc( + method = POST, + path = "/authz/ns/:ns/responsible/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 201, + errorCodes = { 403,404,406,409 }, + text = { "Add an Identity :id to the list of Responsibles for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" } + ) + @Override + public Result addResponsibleNS(AuthzTrans trans, String ns, String id) { + return func.addUserRole(trans,id,ns,Question.OWNER); + } + + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns/responsible/:id", + params = { "ns|string|true", + "id|string|true" + }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Remove an Identity :id to the list of Responsibles for the Namespace :ns", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)", + "Note: A namespace must have at least 1 responsible party" + } + ) + @Override + public Result delResponsibleNS(AuthzTrans trans, String ns, String id) { + return func.delOwner(trans,ns,id); + } + + /* (non-Javadoc) + * @see 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 createNsAttrib(AuthzTrans trans, String ns, String key, String value) { + TimeTaken tt = trans.start("Create NsAttrib " + ns + ':' + key + ':' + value, Env.SUB); + try { + // Check inputs + final Validator v = new Validator(); + if(v.ns(ns).err() || + v.key(key).err() || + v.value(value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Check if exists already + Result> rlnsd = ques.nsDAO.read(trans, ns); + if(rlnsd.notOKorIsEmpty()) { + return Result.err(rlnsd); + } + NsDAO.Data nsd = rlnsd.value.get(0); + + // Check for Existence + if(nsd.attrib.get(key)!=null) { + return Result.err(Status.ERR_ConflictAlreadyExists, "NS Property %s:%s exists", ns, key); + } + + // Check if User may put + if(!ques.isGranted(trans, trans.user(), Define.ROOT_NS, Question.ATTRIB, + ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) { + return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key); + } + + // Add Attrib + nsd.attrib.put(key, value); + ques.nsDAO.dao().attribAdd(trans,ns,key,value); + return Result.ok(); + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authz/ns/attrib/:key", + params = { "key|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { + "Read Attributes for Namespace" + } + ) + @Override + public Result readNsByAttrib(AuthzTrans trans, String key) { + // Check inputs + final Validator v = new Validator(); + if(v.nullOrBlank("Key",key).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // May Read + if(!ques.isGranted(trans, trans.user(), Define.ROOT_NS, Question.ATTRIB, + ":"+trans.org().getDomain()+".*:"+key, Question.READ)) { + return Result.err(Status.ERR_Denied,"%s may not read NS by Attrib '%s'",trans.user(),key); + } + + Result> rsd = ques.nsDAO.dao().readNsByAttrib(trans, key); + if(rsd.notOK()) { + return Result.err(rsd); + } + return mapper().keys(rsd.value); + } + + + @ApiDoc( + method = PUT, + path = "/authz/ns/:ns/attrib/:key/:value", + params = { "ns|string|true", + "key|string|true"}, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { + "Update Value on an existing attribute in the Namespace", + "You must be given direct permission for key by AAF" + } + ) + @Override + public Result updateNsAttrib(AuthzTrans trans, String ns, String key, String value) { + TimeTaken tt = trans.start("Update NsAttrib " + ns + ':' + key + ':' + value, Env.SUB); + try { + // Check inputs + final Validator v = new Validator(); + if(v.ns(ns).err() || + v.key(key).err() || + v.value(value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Check if exists already (NS must exist) + Result> rlnsd = ques.nsDAO.read(trans, ns); + if(rlnsd.notOKorIsEmpty()) { + return Result.err(rlnsd); + } + NsDAO.Data nsd = rlnsd.value.get(0); + + // Check for Existence + if(nsd.attrib.get(key)==null) { + return Result.err(Status.ERR_NotFound, "NS Property %s:%s exists", ns, key); + } + + // Check if User may put + if(!ques.isGranted(trans, trans.user(), Define.ROOT_NS, Question.ATTRIB, + ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) { + return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key); + } + + // Add Attrib + nsd.attrib.put(key, value); + + return ques.nsDAO.update(trans,nsd); + + } finally { + tt.done(); + } + } + + @ApiDoc( + method = DELETE, + path = "/authz/ns/:ns/attrib/:key", + params = { "ns|string|true", + "key|string|true"}, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { + "Delete an attribute in the Namespace", + "You must be given direct permission for key by AAF" + } + ) + @Override + public Result deleteNsAttrib(AuthzTrans trans, String ns, String key) { + TimeTaken tt = trans.start("Delete NsAttrib " + ns + ':' + key, Env.SUB); + try { + // Check inputs + final Validator v = new Validator(); + if(v.nullOrBlank("NS",ns).err() || + v.nullOrBlank("Key",key).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + // Check if exists already + Result> rlnsd = ques.nsDAO.read(trans, ns); + if(rlnsd.notOKorIsEmpty()) { + return Result.err(rlnsd); + } + NsDAO.Data nsd = rlnsd.value.get(0); + + // Check for Existence + if(nsd.attrib.get(key)==null) { + return Result.err(Status.ERR_NotFound, "NS Property [%s:%s] does not exist", ns, key); + } + + // Check if User may del + if(!ques.isGranted(trans, trans.user(), Define.ROOT_NS, "attrib", ":com.att.*:"+key, Access.write.name())) { + return Result.err(Status.ERR_Denied, "%s may not delete NS Attrib [%s:%s]", trans.user(),ns, key); + } + + // Add Attrib + nsd.attrib.remove(key); + ques.nsDAO.dao().attribRemove(trans,ns,key); + return Result.ok(); + } finally { + tt.done(); + } + } + + @ApiDoc( + method = GET, + path = "/authz/nss/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { + "Lists the Admin(s), Responsible Party(s), Role(s), Permission(s)", + "Credential(s) and Expiration of Credential(s) in Namespace :id", + } + ) + @Override + public Result getNSbyName(AuthzTrans trans, String ns) { + final Validator v = new Validator(); + if(v.nullOrBlank("NS", ns).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlnd = ques.nsDAO.read(trans, ns); + if(rlnd.isOK()) { + if(rlnd.isEmpty()) { + return Result.err(Status.ERR_NotFound, "No data found for %s",ns); + } + Result rnd = ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + + Namespace namespace = new Namespace(rnd.value); + Result> rd = func.getOwners(trans, namespace.name, false); + if(rd.isOK()) { + namespace.owner = rd.value; + } + rd = func.getAdmins(trans, namespace.name, false); + if(rd.isOK()) { + namespace.admin = rd.value; + } + + NSS nss = mapper.newInstance(API.NSS); + return mapper.nss(trans, namespace, nss); + } else { + return Result.err(rlnd); + } + } + + @ApiDoc( + method = GET, + path = "/authz/nss/admin/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Namespaces where Identity :id is an Admin", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" + } + ) + @Override + public Result getNSbyAdmin(AuthzTrans trans, String user, boolean full) { + final Validator v = new Validator(); + if (v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData, v.errs()); + } + + Result> rn = loadNamepace(trans, user, ".admin", full); + if(rn.notOK()) { + return Result.err(rn); + } + if (rn.isEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] is not an admin for any namespaces",user); + } + NSS nss = mapper.newInstance(API.NSS); + // Note: "loadNamespace" already validates view of Namespace + return mapper.nss(trans, rn.value, nss); + + } + + @ApiDoc( + method = GET, + path = "/authz/nss/either/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Namespaces where Identity :id is either an Admin or an Owner", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" + } + ) + @Override + public Result getNSbyEither(AuthzTrans trans, String user, boolean full) { + final Validator v = new Validator(); + if (v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData, v.errs()); + } + + Result> rn = loadNamepace(trans, user, null, full); + if(rn.notOK()) { + return Result.err(rn); + } + if (rn.isEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] is not an admin or owner for any namespaces",user); + } + NSS nss = mapper.newInstance(API.NSS); + // Note: "loadNamespace" already validates view of Namespace + return mapper.nss(trans, rn.value, nss); + } + + private Result> loadNamepace(AuthzTrans trans, String user, String endsWith, boolean full) { + Result> urd = ques.userRoleDAO.readByUser(trans, user); + if(urd.notOKorIsEmpty()) { + return Result.err(urd); + } + Map lm = new HashMap(); + Map other = full || endsWith==null?null:new TreeMap(); + for(UserRoleDAO.Data urdd : urd.value) { + if(full) { + if(endsWith==null || urdd.role.endsWith(endsWith)) { + RoleDAO.Data rd = RoleDAO.Data.decode(urdd); + Result nsd = ques.mayUser(trans, user, rd, Access.read); + if(nsd.isOK()) { + Namespace namespace = lm.get(nsd.value.name); + if(namespace==null) { + namespace = new Namespace(nsd.value); + lm.put(namespace.name,namespace); + } + Result> rls = func.getAdmins(trans, namespace.name, false); + if(rls.isOK()) { + namespace.admin=rls.value; + } + + rls = func.getOwners(trans, namespace.name, false); + if(rls.isOK()) { + namespace.owner=rls.value; + } + } + } + } else { // Shortened version. Only Namespace Info available from Role. + if(Question.ADMIN.equals(urdd.rname) || Question.OWNER.equals(urdd.rname)) { + RoleDAO.Data rd = RoleDAO.Data.decode(urdd); + Result nsd = ques.mayUser(trans, user, rd, Access.read); + if(nsd.isOK()) { + Namespace namespace = lm.get(nsd.value.name); + if(namespace==null) { + if(other!=null) { + namespace = other.remove(nsd.value.name); + } + if(namespace==null) { + namespace = new Namespace(nsd.value); + namespace.admin=new ArrayList(); + namespace.owner=new ArrayList(); + } + if(endsWith==null || urdd.role.endsWith(endsWith)) { + lm.put(namespace.name,namespace); + } else { + other.put(namespace.name,namespace); + } + } + if(Question.OWNER.equals(urdd.rname)) { + namespace.owner.add(urdd.user); + } else { + namespace.admin.add(urdd.user); + } + } + } + } + } + return Result.ok(lm.values()); + } + + @ApiDoc( + method = GET, + path = "/authz/nss/responsible/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Namespaces where Identity :id is a Responsible Party", + "Note: :id must be fully qualified (i.e. ab1234@csp.att.com)" + } + ) + @Override + public Result getNSbyResponsible(AuthzTrans trans, String user, boolean full) { + final Validator v = new Validator(); + if (v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData, v.errs()); + } + Result> rn = loadNamepace(trans, user, ".owner",full); + if(rn.notOK()) { + return Result.err(rn); + } + if (rn.isEmpty()) { + return Result.err(Status.ERR_NotFound, "[%s] is not an owner for any namespaces",user); + } + NSS nss = mapper.newInstance(API.NSS); + // Note: "loadNamespace" prevalidates + return mapper.nss(trans, rn.value, nss); + } + + @ApiDoc( + method = GET, + path = "/authz/nss/children/:id", + params = { "id|string|true" }, + expectedCode = 200, + errorCodes = { 403,404 }, + text = { "Lists all Child Namespaces of Namespace :id", + "Note: This is not a cached read" + } + ) + @Override + public Result getNSsChildren(AuthzTrans trans, String parent) { + final Validator v = new Validator(); + if(v.nullOrBlank("NS", parent).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rnd = ques.deriveNs(trans, parent); + if(rnd.notOK()) { + return Result.err(rnd); + } + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + Set lm = new HashSet(); + Result> rlnd = ques.nsDAO.dao().getChildren(trans, parent); + if(rlnd.isOK()) { + if(rlnd.isEmpty()) { + return Result.err(Status.ERR_NotFound, "No data found for %s",parent); + } + for(NsDAO.Data ndd : rlnd.value) { + Namespace namespace = new Namespace(ndd); + Result> rls = func.getAdmins(trans, namespace.name, false); + if(rls.isOK()) { + namespace.admin=rls.value; + } + + rls = func.getOwners(trans, namespace.name, false); + if(rls.isOK()) { + namespace.owner=rls.value; + } + + lm.add(namespace); + } + NSS nss = mapper.newInstance(API.NSS); + return mapper.nss(trans,lm, nss); + } else { + return Result.err(rlnd); + } + } + + + @ApiDoc( + method = PUT, + path = "/authz/ns", + params = {}, + expectedCode = 200, + errorCodes = { 403,404,406 }, + text = { "Replace the Current Description of a Namespace with a new one" + } + ) + @Override + public Result updateNsDescription(AuthzTrans trans, REQUEST from) { + final Result nsd = mapper.ns(trans, from); + final Validator v = new Validator(); + if(v.ns(nsd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + if(v.nullOrBlank("description", nsd.value.description).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Namespace namespace = nsd.value; + Result> rlnd = ques.nsDAO.read(trans, namespace.name); + + if(rlnd.notOKorIsEmpty()) { + return Result.err(Status.ERR_NotFound, "Namespace [%s] does not exist",namespace.name); + } + + if (ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change %s",namespace.name); + } + + Result rdr = ques.nsDAO.dao().addDescription(trans, namespace.name, namespace.description); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + } + + /** + * deleteNS + * @throws DAOException + * @see 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", + "

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

" + + "if the \"force\" property is set to 'force=move', then Permissions and Roles are not deleted," + + "but are retained, and assigned to the Parent Namespace. 'force=move' is not permitted " + + "at or below Application Scope" + } + ) + @Override + public Result deleteNS(AuthzTrans trans, String ns) { + return func.deleteNS(trans, ns); + } + + +/*********************************** + * PERM + ***********************************/ + + /* + * (non-Javadoc) + * @see 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:", + "
  • type - a Namespace qualified identifier specifying what kind of resource " + + "is being protected
  • ", + "
  • instance - a key, possibly multi-dimensional, that identifies a specific " + + " instance of the type
  • ", + "
  • action - what kind of action is allowed
", + "Note: instance and action can be an *" + } + ) + @Override + public Result createPerm(final AuthzTrans trans,REQUEST rreq) { + final Result newPd = mapper.perm(trans, rreq); + final Validator v = new Validator(trans); + if(v.perm(newPd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result fd = mapper.future(trans, PermDAO.TABLE, rreq, newPd.value,false, + new Mapper.Memo() { + @Override + public String get() { + return "Create Permission [" + + newPd.value.fullType() + '|' + + newPd.value.instance + '|' + + newPd.value.action + ']'; + } + }, + new MayChange() { + private Result nsd; + @Override + public Result mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), newPd.value, Access.write); + } + return nsd; + } + }); + Result> nsr = ques.nsDAO.read(trans, newPd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + switch(fd.status) { + case OK: + Result> rfc = func.createFuture(trans,fd.value, + newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action, + trans.user(), + nsr.value.get(0), + "C"); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", + newPd.value.ns, + newPd.value.type, + newPd.value.instance, + newPd.value.action); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.createPerm(trans, newPd.value, true); + default: + return Result.err(fd); + } + } + + @ApiDoc( + method = GET, + path = "/authz/perms/:type", + params = {"type|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match the :type element of the key" } + ) + @Override + public Result getPermsByType(AuthzTrans trans, final String permType) { + final Validator v = new Validator(); + if(v.nullOrBlank("PermType", permType).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlpd = ques.getPermsByType(trans, permType); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + +// We don't have instance & action for mayUserView... do we want to loop through all returned here as well as in mapper? +// Result r; +// if((r = ques.mayUserViewPerm(trans, trans.user(), permType)).notOK())return Result.err(r); + + PERMS perms = mapper.newInstance(API.PERMS); + if(!rlpd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value, perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/:type/:instance/:action", + params = {"type|string|true", + "instance|string|true", + "action|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List Permissions that match key; :type, :instance and :action" } + ) + @Override + public Result getPermsByName(AuthzTrans trans, String type, String instance, String action) { + final Validator v = new Validator(); + if(v.nullOrBlank("PermType", type).err() + || v.nullOrBlank("PermInstance", instance).err() + || v.nullOrBlank("PermAction", action).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlpd = ques.getPermsByName(trans, type, instance, action); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + if(!rlpd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value, perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/user/:user", + params = {"user|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match user :user", + "

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

"} + ) + @Override + public Result getPermsByUser(AuthzTrans trans, String user) { + final Validator v = new Validator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result> rlpd = ques.getPermsByUser(trans, user, trans.forceRequested()); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + + if(rlpd.isEmpty()) { + return Result.ok(perms); + } + // Note: Mapper will restrict what can be viewed + // if user is the same as that which is looked up, no filtering is required + return mapper.perms(trans, rlpd.value, + perms, + !user.equals(trans.user())); + } + + @ApiDoc( + method = POST, + path = "/authz/perms/user/:user", + params = {"user|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that match user :user", + "

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

", + "", + "Present Queries as one or more Permissions (see ContentType Links below for format).", + "", + "If the Caller is Granted this specific Permission, and the Permission is valid", + " for the User, it will be included in response Permissions, along with", + " all the normal permissions on the 'GET' version of this call. If it is not", + " valid, or Caller does not have permission to see, it will be removed from the list", + "", + " *Note: This design allows you to make one call for all expected permissions", + " The permission to be included MUST be:", + " .access|:[:key]|", + " examples:", + " com.att.myns.access|:ns|write", + " com.att.myns.access|:role:myrole|create", + " com.att.myns.access|:perm:mytype:myinstance:myaction|read", + "" + } + ) + @Override + public Result getPermsByUser(AuthzTrans trans, PERMS _perms, String user) { + PERMS perms = _perms; + final Validator v = new Validator(); + if(v.nullOrBlank("User", user).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + ////////////// + Result> rlpd = ques.getPermsByUser(trans, user,trans.forceRequested()); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + /*//TODO + 1) See if allowed to query + 2) See if User is allowed + */ + Result> in = mapper.perms(trans, perms); + if(in.isOKhasData()) { + List out = rlpd.value; + boolean ok; + for(PermDAO.Data pdd : in.value) { + ok = false; + if("access".equals(pdd.type)) { + Access access = Access.valueOf(pdd.action); + String[] mdkey = Split.splitTrim(':',pdd.instance); + if(mdkey.length>1) { + String type = mdkey[1]; + if("role".equals(type)) { + if(mdkey.length>2) { + RoleDAO.Data rdd = new RoleDAO.Data(); + rdd.ns=pdd.ns; + rdd.name=mdkey[2]; + ok = ques.mayUser(trans, trans.user(), rdd, Access.read).isOK() && ques.mayUser(trans, user, rdd , access).isOK(); + } + } else if("perm".equals(type)) { + if(mdkey.length>4) { // also need instance/action + PermDAO.Data p = new PermDAO.Data(); + p.ns=pdd.ns; + p.type=mdkey[2]; + p.instance=mdkey[3]; + p.action=mdkey[4]; + ok = ques.mayUser(trans, trans.user(), p, Access.read).isOK() && ques.mayUser(trans, user, p , access).isOK(); + } + } else if("ns".equals(type)) { + NsDAO.Data ndd = new NsDAO.Data(); + ndd.name=pdd.ns; + ok = ques.mayUser(trans, trans.user(), ndd, Access.read).isOK() && ques.mayUser(trans, user, ndd , access).isOK(); + } + } + } + if(ok) { + out.add(pdd); + } + } + } + + perms = mapper.newInstance(API.PERMS); + if(rlpd.isEmpty()) { + return Result.ok(perms); + } + // Note: Mapper will restrict what can be viewed + // if user is the same as that which is looked up, no filtering is required + return mapper.perms(trans, rlpd.value, + perms, + !user.equals(trans.user())); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/role/:role", + params = {"role|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that are granted to :role" } + ) + @Override + public Result getPermsByRole(AuthzTrans trans,String role) { + final Validator v = new Validator(); + if(v.nullOrBlank("Role", role).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rrdd = RoleDAO.Data.decode(trans, ques,role); + if(rrdd.notOK()) { + return Result.err(rrdd); + } + + Result r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); + if(r.notOK()) { + return Result.err(r); + } + + PERMS perms = mapper.newInstance(API.PERMS); + + Result> rlpd = ques.getPermsByRole(trans, role, trans.forceRequested()); + if(rlpd.isOKhasData()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value, perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = GET, + path = "/authz/perms/ns/:ns", + params = {"ns|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "List All Permissions that are in Namespace :ns" } + ) + @Override + public Result getPermsByNS(AuthzTrans trans,String ns) { + final Validator v = new Validator(); + if(v.nullOrBlank("NS", ns).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result rnd = ques.deriveNs(trans, ns); + if(rnd.notOK()) { + return Result.err(rnd); + } + + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if(rnd.notOK()) { + return Result.err(rnd); + } + + Result> rlpd = ques.permDAO.readNS(trans, ns); + if(rlpd.notOK()) { + return Result.err(rlpd); + } + + PERMS perms = mapper.newInstance(API.PERMS); + if(!rlpd.isEmpty()) { + // Note: Mapper will restrict what can be viewed + return mapper.perms(trans, rlpd.value,perms, true); + } + return Result.ok(perms); + } + + @ApiDoc( + method = PUT, + path = "/authz/perm/:type/:instance/:action", + params = {"type|string|true", + "instance|string|true", + "action|string|true"}, + expectedCode = 200, + errorCodes = { 404,406, 409 }, + text = { "Rename the Permission referenced by :type :instance :action, and " + + "rename (copy/delete) to the Permission described in PermRequest" } + ) + @Override + public Result renamePerm(final AuthzTrans trans,REQUEST rreq, String origType, String origInstance, String origAction) { + final Result newPd = mapper.perm(trans, rreq); + final Validator v = new Validator(trans); + if(v.perm(newPd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + if (ques.mayUser(trans, trans.user(), newPd.value,Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]", + newPd.value.ns,newPd.value.type,newPd.value.instance,newPd.value.action); + } + + Result nss = ques.deriveNsSplit(trans, origType); + Result> origRlpd = ques.permDAO.read(trans, nss.value.ns, nss.value.name, origInstance, origAction); + + if(origRlpd.notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, + "Permission [%s|%s|%s] does not exist", + origType,origInstance,origAction); + } + + PermDAO.Data origPd = origRlpd.value.get(0); + + if (!origPd.ns.equals(newPd.value.ns)) { + return Result.err(Status.ERR_Denied, "Cannot change namespace with rename command. " + + " must start with [" + origPd.ns + "]"); + } + + if ( origPd.type.equals(newPd.value.type) && + origPd.action.equals(newPd.value.action) && + origPd.instance.equals(newPd.value.instance) ) { + return Result.err(Status.ERR_ConflictAlreadyExists, "New Permission must be different than original permission"); + } + + Set origRoles = origPd.roles(false); + if (!origRoles.isEmpty()) { + Set roles = newPd.value.roles(true); + for (String role : origPd.roles) { + roles.add(role); + } + } + + newPd.value.description = origPd.description; + + Result rv = null; + + rv = func.createPerm(trans, newPd.value, false); + if (rv.isOK()) { + rv = func.deletePerm(trans, origPd, true, false); + } + return rv; + } + + @ApiDoc( + method = PUT, + path = "/authz/perm", + params = {}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "Add Description Data to Perm" } + ) + @Override + public Result updatePermDescription(AuthzTrans trans, REQUEST from) { + final Result pd = mapper.perm(trans, from); + final Validator v = new Validator(trans); + if(v.perm(pd).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + if(v.nullOrBlank("description", pd.value.description).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final PermDAO.Data perm = pd.value; + if(ques.permDAO.read(trans, perm.ns, perm.type, perm.instance,perm.action).notOKorIsEmpty()) { + return Result.err(Status.ERR_NotFound, "Permission [%s.%s|%s|%s] does not exist", + perm.ns,perm.type,perm.instance,perm.action); + } + + if (ques.mayUser(trans, trans.user(), perm, Access.write).notOK()) { + return Result.err(Status.ERR_Denied, "You do not have approval to change Permission [%s.%s|%s|%s]", + perm.ns,perm.type,perm.instance,perm.action); + } + + Result> nsr = ques.nsDAO.read(trans, pd.value.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Result rdr = ques.permDAO.addDescription(trans, perm.ns, perm.type, perm.instance, + perm.action, perm.description); + if(rdr.isOK()) { + return Result.ok(); + } else { + return Result.err(rdr); + } + + } + + @ApiDoc( + method = PUT, + path = "/authz/role/perm", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { "Set a permission's roles to roles given" } + ) + + @Override + public Result resetPermRoles(final AuthzTrans trans, REQUEST rreq) { + final Result updt = mapper.permFromRPRequest(trans, rreq); + if(updt.notOKorIsEmpty()) { + return Result.err(updt); + } + + final Validator v = new Validator(trans); + if(v.perm(updt).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result nsd = ques.mayUser(trans, trans.user(), updt.value, Access.write); + if (nsd.notOK()) { + return Result.err(nsd); + } + + // Read full set to get CURRENT values + Result> rcurr = ques.permDAO.read(trans, + updt.value.ns, + updt.value.type, + updt.value.instance, + updt.value.action); + + if(rcurr.notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, + "Permission [%s.%s|%s|%s] does not exist", + updt.value.ns,updt.value.type,updt.value.instance,updt.value.action); + } + + // Create a set of Update Roles, which are in Internal Format + Set updtRoles = new HashSet(); + Result nss; + for(String role : updt.value.roles(false)) { + nss = ques.deriveNsSplit(trans, role); + if(nss.isOK()) { + updtRoles.add(nss.value.ns + '|' + nss.value.name); + } else { + trans.error().log(nss.errorString()); + } + } + + Result rv = null; + + for(PermDAO.Data curr : rcurr.value) { + Set currRoles = curr.roles(false); + // must add roles to this perm, and add this perm to each role + // in the update, but not in the current + for (String role : updtRoles) { + if (!currRoles.contains(role)) { + Result key = RoleDAO.Data.decode(trans, ques, role); + if(key.isOKhasData()) { + Result> rrd = ques.roleDAO.read(trans, key.value); + if(rrd.isOKhasData()) { + for(RoleDAO.Data r : rrd.value) { + rv = func.addPermToRole(trans, r, curr, false); + if (rv.notOK() && rv.status!=Result.ERR_ConflictAlreadyExists) { + return Result.err(rv); + } + } + } else { + return Result.err(rrd); + } + } + } + } + // similarly, must delete roles from this perm, and delete this perm from each role + // in the update, but not in the current + for (String role : currRoles) { + if (!updtRoles.contains(role)) { + Result key = RoleDAO.Data.decode(trans, ques, role); + if(key.isOKhasData()) { + Result> rdd = ques.roleDAO.read(trans, key.value); + if(rdd.isOKhasData()) { + for(RoleDAO.Data r : rdd.value) { + rv = func.delPermFromRole(trans, r, curr, true); + if (rv.notOK() && rv.status!=Status.ERR_PermissionNotFound) { + return Result.err(rv); + } + } + } + } + } + } + } + return rv==null?Result.ok():rv; + } + + @ApiDoc( + method = DELETE, + path = "/authz/perm", + params = {}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "Delete the Permission referenced by PermKey.", + "You cannot normally delete a permission which is still granted to roles,", + "however the \"force\" property allows you to do just that. To do this: Add", + "'force=true' as a query parameter.", + "

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

" } + ) + @Override + public Result deletePerm(final AuthzTrans trans, REQUEST from) { + Result pd = mapper.perm(trans, from); + if(pd.notOK()) { + return Result.err(pd); + } + final Validator v = new Validator(trans); + if(v.nullOrBlank(pd.value).err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + final PermDAO.Data perm = pd.value; + if (ques.permDAO.read(trans, perm).notOKorIsEmpty()) { + return Result.err(Status.ERR_PermissionNotFound, "Permission [%s.%s|%s|%s] does not exist", + perm.ns,perm.type,perm.instance,perm.action ); + } + + Result fd = mapper.future(trans,PermDAO.TABLE,from,perm,false, + new Mapper.Memo() { + @Override + public String get() { + return "Delete Permission [" + perm.fullPerm() + ']'; + } + }, + new MayChange() { + private Result nsd; + @Override + public Result mayChange() { + if(nsd==null) { + nsd = ques.mayUser(trans, trans.user(), perm, Access.write); + } + return nsd; + } + }); + + switch(fd.status) { + case OK: + Result> nsr = ques.nsDAO.read(trans, perm.ns); + if(nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + Result> rfc = func.createFuture(trans, fd.value, + perm.encode(), trans.user(),nsr.value.get(0),"D"); + if(rfc.isOK()) { + return Result.err(Status.ACC_Future, "Perm Deletion [%s] is saved for future processing",perm.encode()); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.deletePerm(trans,perm,trans.forceRequested(), false); + default: + return Result.err(fd); + } + } + + @ApiDoc( + method = DELETE, + path = "/authz/perm/:name/:type/:action", + params = {"type|string|true", + "instance|string|true", + "action|string|true"}, + expectedCode = 200, + errorCodes = { 404,406 }, + text = { "Delete the Permission referenced by :type :instance :action", + "You cannot normally delete a permission which is still granted to roles,", + "however the \"force\" property allows you to do just that. To do this: Add", + "'force=true' as a query parameter", + "

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

"} + ) + @Override + public Result deletePerm(AuthzTrans trans, String type, String instance, String action) { + final Validator v = new Validator(trans); + if(v.nullOrBlank("Type",type) + .nullOrBlank("Instance",instance) + .nullOrBlank("Action",action) + .err()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + Result pd = ques.permFrom(trans, type, instance, action); + if(pd.isOK()) { + return func.deletePerm(trans, pd.value, trans.forceRequested(), false); + } else { + return Result.err(pd); + } + } + +/*********************************** + * ROLE + ***********************************/ + @ApiDoc( + method = POST, + path = "/authz/role", + params = {}, + expectedCode = 201, + errorCodes = {403,404,406,409}, + text = { + + "Roles are part of Namespaces", + "Examples:", + "