From 153f63ef43fd4511026653122fbde27e68221a57 Mon Sep 17 00:00:00 2001 From: Matt Gilman Date: Fri, 15 Apr 2016 15:53:47 -0400 Subject: [PATCH] NIFI-1551: - Removing the AuthorityProvider. - Refactoring REST API in preparation for introduction of the Authorizer. - Updating UI accordingly. - Removing unneeded properties from nifi.properties. - Addressing comments from PR. - This closes #359. --- .../authentication/LoginIdentityProvider.java | 4 +- .../exception/ProviderCreationException.java | 2 +- .../ProviderDestructionException.java | 2 +- .../apache/nifi/authorization/Authority.java | 93 - .../nifi/authorization/AuthorityProvider.java | 182 -- ...AuthorityProviderConfigurationContext.java | 48 - ...uthorityProviderInitializationContext.java | 27 - .../AuthorityProviderLookup.java | 25 - .../authorization/AuthorizationRequest.java | 39 +- .../apache/nifi/authorization/Authorizer.java | 3 +- .../authorization/DownloadAuthorization.java | 83 - .../annotation/AuthorityProviderContext.java | 35 - .../exception/AuthorityAccessException.java | 33 - .../IdentityAlreadyExistsException.java | 32 - .../exception/UnknownIdentityException.java | 32 - nifi-assembly/pom.xml | 8 +- .../org/apache/nifi/util/NiFiProperties.java | 53 +- .../NiFiProperties/conf/nifi.blank.properties | 6 +- .../conf/nifi.missing.properties | 6 +- .../NiFiProperties/conf/nifi.properties | 6 +- .../main/asciidoc/administration-guide.adoc | 139 +- .../cassandra/AbstractCassandraProcessor.java | 2 +- .../AbstractCassandraProcessorTest.java | 2 +- .../nifi-framework-nar/pom.xml | 8 - .../nifi/admin/KeyDataSourceFactoryBean.java | 147 ++ .../nifi/admin/UserDataSourceFactoryBean.java | 244 -- .../apache/nifi/admin/dao/AuthorityDAO.java | 59 - .../org/apache/nifi/admin/dao/DAOFactory.java | 4 - .../org/apache/nifi/admin/dao/UserDAO.java | 128 - .../nifi/admin/dao/impl/DAOFactoryImpl.java | 12 - .../admin/dao/impl/StandardAuthorityDAO.java | 172 -- .../nifi/admin/dao/impl/StandardUserDAO.java | 641 ----- .../service/AccountNotFoundException.java | 40 - .../service/AccountPendingException.java | 41 - ...DisabledException.java => KeyService.java} | 41 +- .../nifi/admin/service/UserService.java | 180 -- .../service/action/AbstractUserAction.java | 97 - .../service/action/AddActionsAction.java | 3 +- .../service/action/AdministrationAction.java | 4 +- .../action/AuthorizeDownloadAction.java | 54 - .../service/action/AuthorizeUserAction.java | 173 -- .../service/action/CreateUserAction.java | 53 - .../service/action/DeleteKeysAction.java | 3 +- .../service/action/DeleteUserAction.java | 73 - .../service/action/DisableUserAction.java | 81 - .../action/DisableUserGroupAction.java | 78 - .../service/action/FindUserByDnAction.java | 49 - .../service/action/FindUserByIdAction.java | 46 - .../admin/service/action/GetActionAction.java | 3 +- .../service/action/GetActionsAction.java | 6 +- .../service/action/GetKeyByIdAction.java | 4 +- .../action/GetKeyByIdentityAction.java | 4 +- .../service/action/GetOrCreateKeyAction.java | 4 +- .../service/action/GetPreviousValues.java | 8 +- .../service/action/GetUserGroupAction.java | 50 - .../admin/service/action/GetUsersAction.java | 39 - .../action/HasPendingUserAccounts.java | 34 - .../action/InvalidateUserAccountAction.java | 58 - .../InvalidateUserGroupAccountsAction.java | 45 - .../service/action/PurgeActionsAction.java | 3 +- .../action/RequestUserAccountAction.java | 67 - .../action/SeedUserAccountsAction.java | 164 -- .../service/action/UngroupUserAction.java | 69 - .../action/UngroupUserGroupAction.java | 57 - .../service/action/UpdateUserAction.java | 124 - .../UpdateUserAuthoritiesCacheAction.java | 73 - .../service/action/UpdateUserCacheAction.java | 47 - .../service/action/UpdateUserGroupAction.java | 171 -- .../service/impl/StandardKeyService.java | 161 ++ .../service/impl/StandardUserService.java | 731 ------ .../transaction/impl/StandardTransaction.java | 16 +- .../impl/StandardTransactionBuilder.java | 8 +- .../AuthorityProviderFactoryBean.java | 491 ---- .../authorization/AuthorizerFactoryBean.java | 11 +- ...AuthorityProviderConfigurationContext.java | 51 - ...uthorityProviderInitializationContext.java | 42 - .../org/apache/nifi/user/AccountStatus.java | 47 - .../java/org/apache/nifi/user/NiFiUser.java | 107 +- .../resources/nifi-administration-context.xml | 33 +- .../src/main/xsd/authority-providers.xsd | 49 - .../action/AuthorizeUserActionTest.java | 433 ---- .../service/action/CreateUserActionTest.java | 144 -- .../service/action/DisableUserActionTest.java | 176 -- .../InvalidateUserAccountActionTest.java | 126 - .../action/RequestUserAccountActionTest.java | 127 - .../action/SeedUserAccountsActionTest.java | 262 -- .../action/SetUserAuthoritiesActionTest.java | 223 -- .../apache/nifi/web/api/dto/RevisionDTO.java | 4 + .../api/dto/status/ControllerStatusDTO.java | 15 - .../apache/nifi/web/api/entity/Entity.java | 6 +- ...trollerServiceReferenceRequestEntity.java} | 46 +- .../.gitignore | 1 - .../pom.xml | 46 - .../ClusterManagerAuthorizationProvider.java | 225 -- .../NodeAuthorizationProvider.java | 389 --- .../protocol/message/DoesDnExistMessage.java | 55 - .../message/GetAuthoritiesMessage.java | 57 - .../protocol/message/ProtocolMessage.java | 56 - .../message/jaxb/JaxbProtocolUtils.java | 41 - .../protocol/message/jaxb/ObjectFactory.java | 44 - ...pache.nifi.authorization.AuthorityProvider | 16 - .../src/test/resources/conf/nifi.properties | 6 +- .../nifi-file-authorization-provider/pom.xml | 85 - .../FileAuthorizationProvider.java | 496 ---- .../src/main/xsd/users.xsd | 64 - .../FileAuthorizationProviderTest.java | 128 - .../nifi/authorization/FileAuthorizer.java | 18 +- .../authorization/FileAuthorizerTest.java | 20 +- .../org/apache/nifi/groups/ProcessGroup.java | 24 + .../nifi/controller/FlowController.java | 20 +- .../nifi/groups/StandardProcessGroup.java | 63 + .../spring/FlowControllerFactoryBean.java | 12 +- .../src/main/resources/nifi-context.xml | 2 +- .../controller/StandardFlowServiceTest.java | 8 +- .../scheduling/TestProcessorLifecycle.java | 4 +- .../src/test/resources/conf/nifi.properties | 6 +- .../resources/nifi-with-remote.properties | 6 +- .../src/test/resources/nifi.properties | 6 +- .../org/apache/nifi/nar/ExtensionManager.java | 19 +- .../nifi/nar/NarThreadContextClassLoader.java | 20 +- .../NarUnpacker/conf/nifi.properties | 6 +- .../main/resources/conf/authorized-users.xml | 57 - ...uthority-providers.xml => authorizers.xml} | 25 +- .../src/main/resources/conf/nifi.properties | 8 +- .../nifi/remote/StandardRootGroupPort.java | 113 +- .../src/test/resources/nifi.properties | 6 +- .../org/apache/nifi/audit/FunnelAuditor.java | 9 +- .../org/apache/nifi/audit/PortAuditor.java | 35 +- .../apache/nifi/audit/ProcessorAuditor.java | 20 +- .../nifi/audit/RelationshipAuditor.java | 18 +- .../nifi/audit/RemoteProcessGroupAuditor.java | 31 +- .../org/apache/nifi/audit/SnippetAuditor.java | 45 +- .../apache/nifi/web/NiFiServiceFacade.java | 279 +-- .../web/NiFiWebApiSecurityConfiguration.java | 82 +- .../nifi/web/StandardNiFiContentAccess.java | 20 +- .../nifi/web/StandardNiFiServiceFacade.java | 624 ++--- .../StandardNiFiWebConfigurationContext.java | 92 +- .../nifi/web/StandardNiFiWebContext.java | 82 +- .../apache/nifi/web/api/AccessResource.java | 79 +- .../nifi/web/api/BulletinBoardResource.java | 37 +- .../apache/nifi/web/api/ClusterResource.java | 11 +- .../nifi/web/api/ConnectionResource.java | 659 +----- .../nifi/web/api/ControllerResource.java | 151 +- .../web/api/ControllerServiceResource.java | 365 +-- .../apache/nifi/web/api/FunnelResource.java | 343 +-- .../apache/nifi/web/api/HistoryResource.java | 60 +- .../nifi/web/api/InputPortResource.java | 340 +-- .../apache/nifi/web/api/LabelResource.java | 387 +-- .../org/apache/nifi/web/api/NodeResource.java | 9 +- .../nifi/web/api/OutputPortResource.java | 383 +-- .../nifi/web/api/ProcessGroupResource.java | 2104 +++++++++++------ .../nifi/web/api/ProcessorResource.java | 485 +--- .../nifi/web/api/ProvenanceResource.java | 112 +- .../web/api/RemoteProcessGroupResource.java | 450 +--- .../nifi/web/api/ReportingTaskResource.java | 344 +-- .../apache/nifi/web/api/SnippetResource.java | 200 +- .../web/api/SystemDiagnosticsResource.java | 3 +- .../apache/nifi/web/api/TemplateResource.java | 49 +- .../nifi/web/api/UserGroupResource.java | 465 ---- .../org/apache/nifi/web/api/UserResource.java | 617 ----- .../AccountNotFoundExceptionMapper.java | 47 - .../apache/nifi/web/api/dto/DtoFactory.java | 99 +- .../nifi/web/controller/ControllerFacade.java | 91 +- .../apache/nifi/web/dao/ConnectionDAO.java | 72 +- .../org/apache/nifi/web/dao/FunnelDAO.java | 25 +- .../org/apache/nifi/web/dao/LabelDAO.java | 15 +- .../java/org/apache/nifi/web/dao/PortDAO.java | 22 +- .../apache/nifi/web/dao/ProcessGroupDAO.java | 4 +- .../org/apache/nifi/web/dao/ProcessorDAO.java | 33 +- .../nifi/web/dao/RemoteProcessGroupDAO.java | 33 +- .../web/dao/impl/StandardConnectionDAO.java | 148 +- .../nifi/web/dao/impl/StandardFunnelDAO.java | 64 +- .../web/dao/impl/StandardInputPortDAO.java | 77 +- .../nifi/web/dao/impl/StandardLabelDAO.java | 59 +- .../web/dao/impl/StandardOutputPortDAO.java | 77 +- .../web/dao/impl/StandardProcessGroupDAO.java | 12 +- .../web/dao/impl/StandardProcessorDAO.java | 93 +- .../impl/StandardRemoteProcessGroupDAO.java | 92 +- .../main/resources/nifi-web-api-context.xml | 57 +- .../AccessTokenEndpointTest.java | 2 + .../accesscontrol/AdminAccessControlTest.java | 2 + .../accesscontrol/DfmAccessControlTest.java | 1 + .../ReadOnlyAccessControlTest.java | 2 + .../util/NiFiTestAuthorizationProvider.java | 180 -- .../integration/util/NiFiTestAuthorizer.java | 56 + .../util/NiFiTestLoginIdentityProvider.java | 9 +- .../nifi/integration/util/NiFiTestServer.java | 2 +- ...pache.nifi.authorization.AuthorityProvider | 15 - .../org.apache.nifi.authorization.Authorizer} | 2 +- .../access-control/authority-providers.xml | 2 +- .../resources/access-control/nifi.properties | 6 +- .../security/NiFiAuthenticationFilter.java | 105 +- .../security/NiFiAuthenticationProvider.java | 73 - .../anonymous/NiFiAnonymousUserFilter.java | 47 +- .../NiFiAuthorizationService.java | 171 -- .../security/jwt/JwtAuthenticationFilter.java | 34 +- .../jwt/JwtAuthenticationProvider.java | 56 + .../JwtAuthenticationRequestToken.java} | 32 +- .../nifi/web/security/jwt/JwtService.java | 12 +- .../node/NodeAuthorizedUserFilter.java | 4 +- .../security/otp/OtpAuthenticationFilter.java | 41 +- .../otp/OtpAuthenticationProvider.java | 60 + .../OtpAuthenticationRequestToken.java} | 38 +- .../KerberosServiceFactoryBean.java | 4 +- .../LoginIdentityProviderFactoryBean.java | 35 +- .../NewAccountAuthorizationRequestToken.java | 40 - ...oken.java => NiFiAuthenticationToken.java} | 4 +- .../web/security/user/NewAccountRequest.java | 47 - .../web/security/user/NiFiUserDetails.java | 17 +- .../nifi/web/security/user/NiFiUserUtils.java | 21 - .../x509/X509AuthenticationFilter.java | 36 +- .../x509/X509AuthenticationProvider.java | 78 + .../x509/X509AuthenticationRequestToken.java | 75 + .../x509/ocsp/OcspCertificateValidator.java | 5 +- .../resources/nifi-web-security-context.xml | 21 +- .../NiFiAuthorizationServiceTest.java | 249 -- .../nifi/web/security/jwt/JwtServiceTest.java | 14 +- .../otp/OtpAuthenticationFilterTest.java | 91 +- .../otp/OtpAuthenticationProviderTest.java | 102 + .../nifi-web/nifi-web-ui/pom.xml | 42 - .../main/resources/filters/canvas.properties | 2 - .../resources/filters/users-min.properties | 18 - .../main/resources/filters/users.properties | 29 - .../src/main/webapp/WEB-INF/pages/canvas.jsp | 2 - .../src/main/webapp/WEB-INF/pages/users.jsp | 72 - .../WEB-INF/partials/canvas/canvas-header.jsp | 1 - .../canvas/secure-port-configuration.jsp | 82 - .../partials/canvas/secure-port-details.jsp | 67 - .../partials/users/group-revoke-dialog.jsp | 22 - .../partials/users/group-roles-dialog.jsp | 52 - .../partials/users/user-delete-dialog.jsp | 23 - .../partials/users/user-details-dialog.jsp | 56 - .../partials/users/user-group-dialog.jsp | 27 - .../partials/users/user-revoke-dialog.jsp | 23 - .../partials/users/user-roles-dialog.jsp | 60 - .../WEB-INF/partials/users/users-content.jsp | 46 - .../src/main/webapp/css/header.css | 13 - .../main/webapp/css/port-configuration.css | 133 -- .../src/main/webapp/css/port-details.css | 27 - .../nifi-web-ui/src/main/webapp/css/users.css | 254 -- .../src/main/webapp/images/iconAdminUser.png | Bin 1960 -> 0 bytes .../propertytable/jquery.propertytable.js | 2 +- .../js/nf/bulletin-board/nf-bulletin-board.js | 2 +- .../main/webapp/js/nf/canvas/nf-actions.js | 140 +- .../webapp/js/nf/canvas/nf-canvas-header.js | 31 +- .../webapp/js/nf/canvas/nf-canvas-toolbox.js | 175 +- .../src/main/webapp/js/nf/canvas/nf-canvas.js | 9 +- .../webapp/js/nf/canvas/nf-component-state.js | 10 +- .../nf/canvas/nf-connection-configuration.js | 108 +- .../main/webapp/js/nf/canvas/nf-connection.js | 35 +- .../js/nf/canvas/nf-controller-service.js | 62 +- .../main/webapp/js/nf/canvas/nf-draggable.js | 26 +- .../src/main/webapp/js/nf/canvas/nf-funnel.js | 9 +- .../src/main/webapp/js/nf/canvas/nf-go-to.js | 24 +- .../js/nf/canvas/nf-label-configuration.js | 33 +- .../src/main/webapp/js/nf/canvas/nf-label.js | 7 + .../js/nf/canvas/nf-port-configuration.js | 31 +- .../src/main/webapp/js/nf/canvas/nf-port.js | 9 +- .../canvas/nf-process-group-configuration.js | 20 +- .../webapp/js/nf/canvas/nf-process-group.js | 7 + .../nf/canvas/nf-processor-configuration.js | 2 +- .../main/webapp/js/nf/canvas/nf-processor.js | 7 + .../webapp/js/nf/canvas/nf-queue-listing.js | 3 +- .../nf-remote-process-group-configuration.js | 1 - .../canvas/nf-remote-process-group-ports.js | 2 - .../js/nf/canvas/nf-remote-process-group.js | 7 + .../webapp/js/nf/canvas/nf-reporting-task.js | 23 +- .../nf/canvas/nf-secure-port-configuration.js | 384 --- .../js/nf/canvas/nf-secure-port-details.js | 121 - .../main/webapp/js/nf/canvas/nf-settings.js | 42 +- .../main/webapp/js/nf/canvas/nf-snippet.js | 2 +- .../webapp/js/nf/history/nf-history-model.js | 2 +- .../webapp/js/nf/history/nf-history-table.js | 2 +- .../webapp/js/nf/nf-connection-details.js | 16 +- .../main/webapp/js/nf/nf-processor-details.js | 4 +- .../main/webapp/js/nf/nf-status-history.js | 9 +- .../webapp/js/nf/summary/nf-cluster-search.js | 2 +- .../webapp/js/nf/summary/nf-summary-table.js | 15 +- .../main/webapp/js/nf/users/nf-users-table.js | 1075 --------- .../src/main/webapp/js/nf/users/nf-users.js | 151 -- .../nifi-framework/pom.xml | 2 - .../nifi-framework-bundle/pom.xml | 10 - .../nifi/kerberos/KerberosProvider.java | 4 +- .../org/apache/nifi/ldap/LdapProvider.java | 4 +- 284 files changed, 4804 insertions(+), 20562 deletions(-) rename nifi-api/src/main/java/org/apache/nifi/{authorization => authentication}/exception/ProviderCreationException.java (96%) rename nifi-api/src/main/java/org/apache/nifi/{authorization => authentication}/exception/ProviderDestructionException.java (96%) delete mode 100644 nifi-api/src/main/java/org/apache/nifi/authorization/Authority.java delete mode 100644 nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProvider.java delete mode 100644 nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderConfigurationContext.java delete mode 100644 nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderInitializationContext.java delete mode 100644 nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderLookup.java delete mode 100644 nifi-api/src/main/java/org/apache/nifi/authorization/DownloadAuthorization.java delete mode 100644 nifi-api/src/main/java/org/apache/nifi/authorization/annotation/AuthorityProviderContext.java delete mode 100644 nifi-api/src/main/java/org/apache/nifi/authorization/exception/AuthorityAccessException.java delete mode 100644 nifi-api/src/main/java/org/apache/nifi/authorization/exception/IdentityAlreadyExistsException.java delete mode 100644 nifi-api/src/main/java/org/apache/nifi/authorization/exception/UnknownIdentityException.java create mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/KeyDataSourceFactoryBean.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/UserDataSourceFactoryBean.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/AuthorityDAO.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/UserDAO.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/StandardAuthorityDAO.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/StandardUserDAO.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountNotFoundException.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountPendingException.java rename nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/{AccountDisabledException.java => KeyService.java} (53%) delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/UserService.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AbstractUserAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AuthorizeDownloadAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AuthorizeUserAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/CreateUserAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DeleteUserAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DisableUserAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DisableUserGroupAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/FindUserByDnAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/FindUserByIdAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetUserGroupAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetUsersAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/HasPendingUserAccounts.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/InvalidateUserAccountAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/InvalidateUserGroupAccountsAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/RequestUserAccountAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/SeedUserAccountsAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UngroupUserAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UngroupUserGroupAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserAuthoritiesCacheAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserCacheAction.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserGroupAction.java create mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/impl/StandardKeyService.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/impl/StandardUserService.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/AuthorityProviderFactoryBean.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/StandardAuthorityProviderConfigurationContext.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/StandardAuthorityProviderInitializationContext.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/user/AccountStatus.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/xsd/authority-providers.xsd delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/AuthorizeUserActionTest.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/CreateUserActionTest.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/DisableUserActionTest.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/InvalidateUserAccountActionTest.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/RequestUserAccountActionTest.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/SeedUserAccountsActionTest.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/SetUserAuthoritiesActionTest.java rename nifi-nar-bundles/nifi-framework-bundle/nifi-framework/{nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/GetGroupForUserMessage.java => nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/UpdateControllerServiceReferenceRequestEntity.java} (50%) delete mode 100755 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/.gitignore delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/pom.xml delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/ClusterManagerAuthorizationProvider.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/NodeAuthorizationProvider.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/DoesDnExistMessage.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/GetAuthoritiesMessage.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/ProtocolMessage.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/jaxb/JaxbProtocolUtils.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/jaxb/ObjectFactory.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/pom.xml delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/java/org/apache/nifi/authorization/FileAuthorizationProvider.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/xsd/users.xsd delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/test/java/org/apache/nifi/authorization/FileAuthorizationProviderTest.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-resources/src/main/resources/conf/authorized-users.xml rename nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-resources/src/main/resources/conf/{authority-providers.xml => authorizers.xml} (53%) delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/UserGroupResource.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/UserResource.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/config/AccountNotFoundExceptionMapper.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestAuthorizationProvider.java create mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestAuthorizer.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider rename nifi-nar-bundles/nifi-framework-bundle/nifi-framework/{nifi-file-authorization-provider/src/main/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider => nifi-web/nifi-web-api/src/test/resources/META-INF/services/org.apache.nifi.authorization.Authorizer} (93%) mode change 100755 => 100644 delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationProvider.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationService.java create mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationProvider.java rename nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/{token/NewAccountAuthorizationToken.java => jwt/JwtAuthenticationRequestToken.java} (59%) create mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationProvider.java rename nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/{token/NiFiAuthorizationRequestToken.java => otp/OtpAuthenticationRequestToken.java} (57%) rename nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/{kerberos => spring}/KerberosServiceFactoryBean.java (94%) delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NewAccountAuthorizationRequestToken.java rename nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/{NiFiAuthorizationToken.java => NiFiAuthenticationToken.java} (92%) delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NewAccountRequest.java create mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationProvider.java create mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationRequestToken.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationServiceTest.java create mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/otp/OtpAuthenticationProviderTest.java delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/users-min.properties delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/users.properties delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/pages/users.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/secure-port-configuration.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/secure-port-details.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/group-revoke-dialog.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/group-roles-dialog.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-delete-dialog.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-details-dialog.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-group-dialog.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-revoke-dialog.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-roles-dialog.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/users-content.jsp delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/users.css delete mode 100755 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/images/iconAdminUser.png delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-secure-port-configuration.js delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-secure-port-details.js delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/users/nf-users-table.js delete mode 100644 nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/users/nf-users.js diff --git a/nifi-api/src/main/java/org/apache/nifi/authentication/LoginIdentityProvider.java b/nifi-api/src/main/java/org/apache/nifi/authentication/LoginIdentityProvider.java index 54becb37cb..145bdb49e8 100644 --- a/nifi-api/src/main/java/org/apache/nifi/authentication/LoginIdentityProvider.java +++ b/nifi-api/src/main/java/org/apache/nifi/authentication/LoginIdentityProvider.java @@ -18,8 +18,8 @@ package org.apache.nifi.authentication; import org.apache.nifi.authentication.exception.IdentityAccessException; import org.apache.nifi.authentication.exception.InvalidLoginCredentialsException; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.authorization.exception.ProviderDestructionException; +import org.apache.nifi.authentication.exception.ProviderCreationException; +import org.apache.nifi.authentication.exception.ProviderDestructionException; /** * Identity provider that is able to authentication a user with username/password credentials. diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/exception/ProviderCreationException.java b/nifi-api/src/main/java/org/apache/nifi/authentication/exception/ProviderCreationException.java similarity index 96% rename from nifi-api/src/main/java/org/apache/nifi/authorization/exception/ProviderCreationException.java rename to nifi-api/src/main/java/org/apache/nifi/authentication/exception/ProviderCreationException.java index 24ac7938e7..b352787712 100644 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/exception/ProviderCreationException.java +++ b/nifi-api/src/main/java/org/apache/nifi/authentication/exception/ProviderCreationException.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.nifi.authorization.exception; +package org.apache.nifi.authentication.exception; /** * Represents the exceptional case when an AuthorityProvider fails instantiated. diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/exception/ProviderDestructionException.java b/nifi-api/src/main/java/org/apache/nifi/authentication/exception/ProviderDestructionException.java similarity index 96% rename from nifi-api/src/main/java/org/apache/nifi/authorization/exception/ProviderDestructionException.java rename to nifi-api/src/main/java/org/apache/nifi/authentication/exception/ProviderDestructionException.java index 985d3fbdf8..1e12146938 100644 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/exception/ProviderDestructionException.java +++ b/nifi-api/src/main/java/org/apache/nifi/authentication/exception/ProviderDestructionException.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.nifi.authorization.exception; +package org.apache.nifi.authentication.exception; /** * Represents the exceptional case when an AuthorityProvider fails destruction. diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/Authority.java b/nifi-api/src/main/java/org/apache/nifi/authorization/Authority.java deleted file mode 100644 index 4502c1196f..0000000000 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/Authority.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -import java.util.EnumSet; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; - -/** - * Authorities that can be assigned to NiFi users. - */ -public enum Authority { - - ROLE_MONITOR, - ROLE_DFM, - ROLE_ADMIN, - ROLE_PROVENANCE, - ROLE_PROXY, - ROLE_NIFI; - - /** - * @param rawAuthority string form of authority - * @return the matching role or null if the specified role does not match - * any roles - */ - public static Authority valueOfAuthority(String rawAuthority) { - Authority desiredAuthority = null; - - for (Authority authority : values()) { - if (authority.toString().equals(rawAuthority)) { - desiredAuthority = authority; - break; - } - } - - return desiredAuthority; - } - - /** - * @return the string value of each authority - */ - public static Set getRawAuthorities() { - Set authorities = new LinkedHashSet<>(); - for (Authority authority : values()) { - authorities.add(authority.toString()); - } - return authorities; - } - - public static Set convertAuthorities(Set authorities) { - if (authorities == null) { - throw new IllegalArgumentException("No authorities have been specified."); - } - - // convert the set - Set rawAuthorities = new HashSet<>(authorities.size()); - for (Authority authority : authorities) { - rawAuthorities.add(authority.toString()); - } - return rawAuthorities; - } - - public static EnumSet convertRawAuthorities(Set rawAuthorities) { - if (rawAuthorities == null) { - throw new IllegalArgumentException("No authorities have been specified."); - } - - // convert the set - EnumSet authorities = EnumSet.noneOf(Authority.class); - for (String rawAuthority : rawAuthorities) { - Authority authority = Authority.valueOfAuthority(rawAuthority); - if (authority != null) { - authorities.add(authority); - } - } - return authorities; - } -} diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProvider.java b/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProvider.java deleted file mode 100644 index 716216d127..0000000000 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProvider.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.IdentityAlreadyExistsException; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.authorization.exception.ProviderDestructionException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; - -/** - * This class allows clients to retrieve the authorities for a given DN. - */ -public interface AuthorityProvider { - - /** - * @param identity of the user. The identity may be a dn, an email, a username, or any string that identities the user. - * @return whether the user with the specified identity is known to this authority - * provider. It is not necessary for the user to have any authorities - */ - boolean doesDnExist(String identity) throws AuthorityAccessException; - - /** - * Get the authorities for the specified user. If the specified user exists - * but does not have any authorities, an empty set should be returned. - * - * @param identity of the user. The identity may be a dn, an email, a username, or any string that identities the user. - * @return the authorities for the specified user. If the specified user - * exists but does not have any authorities, an empty set should be returned - * @throws UnknownIdentityException if identity is not known - * @throws AuthorityAccessException if unable to access authorities - */ - Set getAuthorities(String identity) throws UnknownIdentityException, AuthorityAccessException; - - /** - * Sets the specified authorities for the specified user. - * - * @param identity of the user. The identity may be a dn, an email, a username, or any string that identities the user. - * @param authorities the new authorities for the user - * @throws UnknownIdentityException if identity is not known - * @throws AuthorityAccessException if unable to access authorities - */ - void setAuthorities(String identity, Set authorities) throws UnknownIdentityException, AuthorityAccessException; - - /** - * Gets the users for the specified authority. - * - * @param authority for which to determine membership of - * @return all users with the specified authority - * @throws AuthorityAccessException if unable to access authorities - */ - Set getUsers(Authority authority) throws AuthorityAccessException; - - /** - * Revokes the specified user. Its up to the implementor to determine the - * semantics of revocation. - * - * @param identity of the user. The identity may be a dn, an email, a username, or any string that identities the user. - * @throws UnknownIdentityException if the user is not known - * @throws AuthorityAccessException if unable to access the authorities - */ - void revokeUser(String identity) throws UnknownIdentityException, AuthorityAccessException; - - /** - * Add the specified user. - * - * @param identity of the user. The identity may be a dn, an email, a username, or any string that identities the user. - * @param group Optional - * @throws UnknownIdentityException if the user is not known - * @throws AuthorityAccessException if unable to access the authorities - */ - void addUser(String identity, String group) throws IdentityAlreadyExistsException, AuthorityAccessException; - - /** - * Gets the group for the specified user. Return null if the user does not - * belong to a group. - * - * @param identity of the user. The identity may be a dn, an email, a username, or any string that identities the user. - * @return the group of the given user - * @throws UnknownIdentityException if the user is not known - * @throws AuthorityAccessException if unable to access the authorities - */ - String getGroupForUser(String identity) throws UnknownIdentityException, AuthorityAccessException; - - /** - * Revokes all users for a specified group. Its up to the implementor to - * determine the semantics of revocation. - * - * @param group to revoke the users of - * @throws UnknownIdentityException if the user is not known - * @throws AuthorityAccessException if unable to access the authorities - */ - void revokeGroup(String group) throws UnknownIdentityException, AuthorityAccessException; - - /** - * Adds the specified users to the specified group. - * - * @param identity of the user. The identity may be a dn, an email, a username, or any string that identities the user. - * @param group to add users to - * @throws UnknownIdentityException if the user is not known - * @throws AuthorityAccessException if unable to access the authorities - */ - void setUsersGroup(Set identity, String group) throws UnknownIdentityException, AuthorityAccessException; - - /** - * Ungroups the specified user. - * - * @param identity of the user. The identity may be a dn, an email, a username, or any string that identities the user. - * @throws UnknownIdentityException if the user is not known - * @throws AuthorityAccessException if unable to access the authorities - */ - void ungroupUser(String identity) throws UnknownIdentityException, AuthorityAccessException; - - /** - * Ungroups the specified group. Since the semantics of revocation is up to - * the implementor, this method should do nothing if the specified group - * does not exist. If an admin revoked this group before calling ungroup, it - * may or may not exist. - * - * @param group to ungroup - * @throws AuthorityAccessException if unable to access the authorities - */ - void ungroup(String group) throws AuthorityAccessException; - - /** - * Determines whether the user in the specified dnChain should be able to - * download the content for the flowfile with the specified attributes. - * - * The first identity in the chain is the end user that the request was issued on - * behalf of. The subsequent identities in the chain represent entities proxying - * the user's request with the last being the proxy that sent the current - * request. - * - * @param proxyChain proxy chain of user identities that for the download request - * @param attributes of the flowfile being requested - * @return the authorization result - * @throws UnknownIdentityException if the user is not known - * @throws AuthorityAccessException if unable to access the authorities - */ - DownloadAuthorization authorizeDownload(List proxyChain, Map attributes) throws UnknownIdentityException, AuthorityAccessException; - - /** - * Called immediately after instance creation for implementers to perform - * additional setup - * - * @param initializationContext in which to initialize - */ - void initialize(AuthorityProviderInitializationContext initializationContext) throws ProviderCreationException; - - /** - * Called to configure the AuthorityProvider. - * - * @param configurationContext at the time of configuration - * @throws ProviderCreationException for any issues configuring the provider - */ - void onConfigured(AuthorityProviderConfigurationContext configurationContext) throws ProviderCreationException; - - /** - * Called immediately before instance destruction for implementers to - * release resources. - * - * @throws ProviderDestructionException If pre-destruction fails. - */ - void preDestruction() throws ProviderDestructionException; -} diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderConfigurationContext.java b/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderConfigurationContext.java deleted file mode 100644 index c1ba5dfd80..0000000000 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderConfigurationContext.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -import java.util.Map; - -/** - * - */ -public interface AuthorityProviderConfigurationContext { - - /** - * @return identifier for the authority provider - */ - String getIdentifier(); - - /** - * Retrieves all properties the component currently understands regardless - * of whether a value has been set for them or not. If no value is present - * then its value is null and thus any registered default for the property - * descriptor applies. - * - * @return Map of all properties - */ - Map getProperties(); - - /** - * @param property to lookup the descriptor and value of - * @return the value the component currently understands for the given - * PropertyDescriptor. This method does not substitute default - * PropertyDescriptor values, so the value returned will be null if not set - */ - String getProperty(String property); -} diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderInitializationContext.java b/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderInitializationContext.java deleted file mode 100644 index 7b2f89fa92..0000000000 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderInitializationContext.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -/** - * - */ -public interface AuthorityProviderInitializationContext { - - public String getIdentifier(); - - public AuthorityProviderLookup getAuthorityProviderLookup(); -} diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderLookup.java b/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderLookup.java deleted file mode 100644 index dc30967209..0000000000 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorityProviderLookup.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -/** - * - */ -public interface AuthorityProviderLookup { - - AuthorityProvider getAuthorityProvider(String identifier); -} diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorizationRequest.java b/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorizationRequest.java index 9e50e62cda..7e6999c09a 100644 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorizationRequest.java +++ b/nifi-api/src/main/java/org/apache/nifi/authorization/AuthorizationRequest.java @@ -29,17 +29,22 @@ public class AuthorizationRequest { private final Resource resource; private final String identity; private final RequestAction action; + private final boolean isAccessAttempt; + private final boolean isAnonymous; private final Map context; private final Map eventAttributes; private AuthorizationRequest(final Builder builder) { Objects.requireNonNull(builder.resource, "The resource is required when creating an authorization request"); - Objects.requireNonNull(builder.identity, "The identity of the user is required when creating an authorization request"); Objects.requireNonNull(builder.action, "The action is required when creating an authorization request"); + Objects.requireNonNull(builder.isAccessAttempt, "Whether this request is an access attempt is request"); + Objects.requireNonNull(builder.isAnonymous, "Whether this request is being performed by an anonymous user is required"); this.resource = builder.resource; this.identity = builder.identity; this.action = builder.action; + this.isAccessAttempt = builder.isAccessAttempt; + this.isAnonymous = builder.isAnonymous; this.context = builder.context == null ? null : Collections.unmodifiableMap(builder.context); this.eventAttributes = builder.context == null ? null : Collections.unmodifiableMap(builder.eventAttributes); } @@ -54,7 +59,7 @@ public class AuthorizationRequest { } /** - * The identity accessing the Resource. Not null. + * The identity accessing the Resource. May be null if the user could not authenticate. * * @return The identity */ @@ -62,6 +67,24 @@ public class AuthorizationRequest { return identity; } + /** + * Whether this is a direct access attempt of the Resource if if it's being checked as part of another response. + * + * @return if this is a direct access attempt + */ + public boolean isAccessAttempt() { + return isAccessAttempt; + } + + /** + * Whether the entity accessing is anonymous. + * + * @return whether the entity is anonymous + */ + public boolean isAnonymous() { + return isAnonymous; + } + /** * The action being taken against the Resource. Not null. * @@ -96,6 +119,8 @@ public class AuthorizationRequest { private Resource resource; private String identity; + private Boolean isAnonymous; + private Boolean isAccessAttempt; private RequestAction action; private Map context; private Map eventAttributes; @@ -110,6 +135,16 @@ public class AuthorizationRequest { return this; } + public Builder anonymous(final Boolean isAnonymous) { + this.isAnonymous = isAnonymous; + return this; + } + + public Builder accessAttempt(final Boolean isAccessAttempt) { + this.isAccessAttempt = isAccessAttempt; + return this; + } + public Builder action(final RequestAction action) { this.action = action; return this; diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/Authorizer.java b/nifi-api/src/main/java/org/apache/nifi/authorization/Authorizer.java index 01a76e45cd..5aec6f0b0b 100644 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/Authorizer.java +++ b/nifi-api/src/main/java/org/apache/nifi/authorization/Authorizer.java @@ -16,7 +16,6 @@ */ package org.apache.nifi.authorization; -import org.apache.nifi.authorization.exception.AuthorityAccessException; import org.apache.nifi.authorization.exception.AuthorizationAccessException; import org.apache.nifi.authorization.exception.AuthorizerCreationException; import org.apache.nifi.authorization.exception.AuthorizerDestructionException; @@ -31,7 +30,7 @@ public interface Authorizer { * * @param request The authorization request * @return the authorization result - * @throws AuthorityAccessException if unable to access the authorities + * @throws AuthorizationAccessException if unable to access the authorities */ AuthorizationResult authorize(AuthorizationRequest request) throws AuthorizationAccessException; diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/DownloadAuthorization.java b/nifi-api/src/main/java/org/apache/nifi/authorization/DownloadAuthorization.java deleted file mode 100644 index 416f3cfe7d..0000000000 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/DownloadAuthorization.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -/** - * Represents a decision whether authorization is granted to download content. - */ -public class DownloadAuthorization { - - private static enum Result { - - Approved, - Denied; - } - - private static final DownloadAuthorization APPROVED = new DownloadAuthorization(Result.Approved, null); - - private final Result result; - private final String explanation; - - /** - * Creates a new DownloadAuthorization with the specified result and - * explanation. - * - * @param result of the authorization - * @param explanation for the authorization attempt - */ - private DownloadAuthorization(Result result, String explanation) { - if (Result.Denied.equals(result) && explanation == null) { - throw new IllegalArgumentException("An explanation is required when the download request is denied."); - } - - this.result = result; - this.explanation = explanation; - } - - /** - * @return Whether or not the download request is approved - */ - public boolean isApproved() { - return Result.Approved.equals(result); - } - - /** - * @return If the download request is denied, the reason why. Null otherwise - */ - public String getExplanation() { - return explanation; - } - - /** - * @return a new approved DownloadAuthorization - */ - public static DownloadAuthorization approved() { - return APPROVED; - } - - /** - * Creates a new denied DownloadAuthorization with the specified - * explanation. - * - * @param explanation for why it was denied - * @return a new denied DownloadAuthorization with the specified explanation - * @throws IllegalArgumentException if explanation is null - */ - public static DownloadAuthorization denied(String explanation) { - return new DownloadAuthorization(Result.Denied, explanation); - } -} diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/annotation/AuthorityProviderContext.java b/nifi-api/src/main/java/org/apache/nifi/authorization/annotation/AuthorityProviderContext.java deleted file mode 100644 index 5ac2af7450..0000000000 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/annotation/AuthorityProviderContext.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * - * - */ -@Documented -@Target({ElementType.FIELD, ElementType.METHOD}) -@Retention(RetentionPolicy.RUNTIME) -@Inherited -public @interface AuthorityProviderContext { -} diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/exception/AuthorityAccessException.java b/nifi-api/src/main/java/org/apache/nifi/authorization/exception/AuthorityAccessException.java deleted file mode 100644 index be64767999..0000000000 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/exception/AuthorityAccessException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization.exception; - -/** - * Represents the case when the DN could not be confirmed because it was unable - * to access the data store. - */ -public class AuthorityAccessException extends RuntimeException { - - public AuthorityAccessException(String message, Throwable cause) { - super(message, cause); - } - - public AuthorityAccessException(String message) { - super(message); - } - -} diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/exception/IdentityAlreadyExistsException.java b/nifi-api/src/main/java/org/apache/nifi/authorization/exception/IdentityAlreadyExistsException.java deleted file mode 100644 index ba80b6e109..0000000000 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/exception/IdentityAlreadyExistsException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization.exception; - -/** - * Represents the case when the user identity already exists. - */ -public class IdentityAlreadyExistsException extends RuntimeException { - - public IdentityAlreadyExistsException(String message, Throwable cause) { - super(message, cause); - } - - public IdentityAlreadyExistsException(String message) { - super(message); - } - -} diff --git a/nifi-api/src/main/java/org/apache/nifi/authorization/exception/UnknownIdentityException.java b/nifi-api/src/main/java/org/apache/nifi/authorization/exception/UnknownIdentityException.java deleted file mode 100644 index 2ada1c78ec..0000000000 --- a/nifi-api/src/main/java/org/apache/nifi/authorization/exception/UnknownIdentityException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization.exception; - -/** - * Represents the case when an identity cannot be confirmed. - */ -public class UnknownIdentityException extends RuntimeException { - - public UnknownIdentityException(String message, Throwable cause) { - super(message, cause); - } - - public UnknownIdentityException(String message) { - super(message); - } - -} diff --git a/nifi-assembly/pom.xml b/nifi-assembly/pom.xml index 09a8d5016b..e85c83f132 100644 --- a/nifi-assembly/pom.xml +++ b/nifi-assembly/pom.xml @@ -325,7 +325,7 @@ language governing permissions and limitations under the License. --> ./conf/flow.xml.gz ./conf/archive/ ./conf/login-identity-providers.xml - ./conf/authority-providers.xml + ./conf/authorizers.xml ./conf/templates ./database_repository @@ -413,13 +413,9 @@ language governing permissions and limitations under the License. --> - ./conf/authorized-users.xml - 24 hours - file-provider + file-provider - - diff --git a/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java b/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java index 517b19a65a..63693bf00e 100644 --- a/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java +++ b/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java @@ -28,14 +28,10 @@ import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.Set; public class NiFiProperties extends Properties { @@ -48,7 +44,7 @@ public class NiFiProperties extends Properties { public static final String PROPERTIES_FILE_PATH = "nifi.properties.file.path"; public static final String FLOW_CONFIGURATION_FILE = "nifi.flow.configuration.file"; public static final String FLOW_CONFIGURATION_ARCHIVE_FILE = "nifi.flow.configuration.archive.file"; - public static final String AUTHORITY_PROVIDER_CONFIGURATION_FILE = "nifi.authority.provider.configuration.file"; + public static final String AUTHORIZER_CONFIGURATION_FILE = "nifi.authorizer.configuration.file"; public static final String LOGIN_IDENTITY_PROVIDER_CONFIGURATION_FILE = "nifi.login.identity.provider.configuration.file"; public static final String REPOSITORY_DATABASE_DIRECTORY = "nifi.database.directory"; public static final String RESTORE_DIRECTORY = "nifi.restore.directory"; @@ -131,13 +127,10 @@ public class NiFiProperties extends Properties { public static final String SECURITY_TRUSTSTORE_TYPE = "nifi.security.truststoreType"; public static final String SECURITY_TRUSTSTORE_PASSWD = "nifi.security.truststorePasswd"; public static final String SECURITY_NEED_CLIENT_AUTH = "nifi.security.needClientAuth"; - public static final String SECURITY_USER_AUTHORITY_PROVIDER = "nifi.security.user.authority.provider"; + public static final String SECURITY_USER_AUTHORIZER = "nifi.security.user.authorizer"; public static final String SECURITY_USER_LOGIN_IDENTITY_PROVIDER = "nifi.security.user.login.identity.provider"; public static final String SECURITY_CLUSTER_AUTHORITY_PROVIDER_PORT = "nifi.security.cluster.authority.provider.port"; public static final String SECURITY_CLUSTER_AUTHORITY_PROVIDER_THREADS = "nifi.security.cluster.authority.provider.threads"; - public static final String SECURITY_USER_CREDENTIAL_CACHE_DURATION = "nifi.security.user.credential.cache.duration"; - public static final String SECURITY_SUPPORT_NEW_ACCOUNT_REQUESTS = "nifi.security.support.new.account.requests"; - public static final String SECURITY_ANONYMOUS_AUTHORITIES = "nifi.security.anonymous.authorities"; public static final String SECURITY_OCSP_RESPONDER_URL = "nifi.security.ocsp.responder.url"; public static final String SECURITY_OCSP_RESPONDER_CERTIFICATE = "nifi.security.ocsp.responder.certificate"; @@ -504,10 +497,10 @@ public class NiFiProperties extends Properties { } /** - * @return the user authorities file + * @return the user authorizers file */ - public File getAuthorityProviderConfiguraitonFile() { - final String value = getProperty(AUTHORITY_PROVIDER_CONFIGURATION_FILE); + public File getAuthorizerConfiguraitonFile() { + final String value = getProperty(AUTHORIZER_CONFIGURATION_FILE); if (StringUtils.isBlank(value)) { return new File(DEFAULT_AUTHORITY_PROVIDER_CONFIGURATION_FILE); } else { @@ -541,40 +534,6 @@ public class NiFiProperties extends Properties { return needClientAuth; } - public String getUserCredentialCacheDuration() { - return getProperty(SECURITY_USER_CREDENTIAL_CACHE_DURATION, - DEFAULT_USER_CREDENTIAL_CACHE_DURATION); - } - - public boolean getSupportNewAccountRequests() { - boolean shouldSupport = true; - String rawShouldSupport = getProperty(SECURITY_SUPPORT_NEW_ACCOUNT_REQUESTS); - if ("false".equalsIgnoreCase(rawShouldSupport)) { - shouldSupport = false; - } - return shouldSupport; - } - - @SuppressWarnings("unchecked") - public Set getAnonymousAuthorities() { - final Set authorities; - - final String rawAnonymousAuthorities = getProperty(SECURITY_ANONYMOUS_AUTHORITIES); - if (!StringUtils.isEmpty(rawAnonymousAuthorities)) { - authorities = new HashSet<>(); - - // parse the raw authorities and trim them - final List authoritiesList = Arrays.asList(rawAnonymousAuthorities.split(",")); - for (final String authority : authoritiesList) { - authorities.add(authority.trim()); - } - } else { - authorities = Collections.EMPTY_SET; - } - - return authorities; - } - // getters for web properties // public Integer getPort() { Integer port = null; @@ -922,7 +881,7 @@ public class NiFiProperties extends Properties { * @return true if client certificates are required for access to the REST API */ public boolean isClientAuthRequiredForRestApi() { - return StringUtils.isBlank(getProperty(NiFiProperties.SECURITY_USER_LOGIN_IDENTITY_PROVIDER)) && getAnonymousAuthorities().isEmpty() && !isKerberosServiceSupportEnabled(); + return StringUtils.isBlank(getProperty(NiFiProperties.SECURITY_USER_LOGIN_IDENTITY_PROVIDER)) && !isKerberosServiceSupportEnabled(); } public InetSocketAddress getNodeApiAddress() { diff --git a/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.blank.properties b/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.blank.properties index 720c05019d..898cebf10c 100644 --- a/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.blank.properties +++ b/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.blank.properties @@ -83,11 +83,7 @@ nifi.security.truststore= nifi.security.truststoreType= nifi.security.truststorePasswd= nifi.security.needClientAuth= -nifi.security.authorizedUsers.file=./target/conf/authorized-users.xml -nifi.security.user.credential.cache.duration=24 hours -nifi.security.user.authority.provider=nifi.authorization.FileAuthorizationProvider -nifi.security.support.new.account.requests= -nifi.security.default.user.roles= +nifi.security.user.authorizer= # cluster common properties (cluster manager and nodes must have same values) # nifi.cluster.protocol.heartbeat.interval=5 sec diff --git a/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.missing.properties b/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.missing.properties index 85300ae076..786b05f47b 100644 --- a/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.missing.properties +++ b/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.missing.properties @@ -81,11 +81,7 @@ nifi.security.truststore= nifi.security.truststoreType= nifi.security.truststorePasswd= nifi.security.needClientAuth= -nifi.security.authorizedUsers.file=./target/conf/authorized-users.xml -nifi.security.user.credential.cache.duration=24 hours -nifi.security.user.authority.provider=nifi.authorization.FileAuthorizationProvider -nifi.security.support.new.account.requests= -nifi.security.default.user.roles= +nifi.security.user.authorizer= # cluster common properties (cluster manager and nodes must have same values) # nifi.cluster.protocol.heartbeat.interval=5 sec diff --git a/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.properties b/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.properties index 0ace99e401..f9d9b78ee8 100644 --- a/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.properties +++ b/nifi-commons/nifi-properties/src/test/resources/NiFiProperties/conf/nifi.properties @@ -83,11 +83,7 @@ nifi.security.truststore= nifi.security.truststoreType= nifi.security.truststorePasswd= nifi.security.needClientAuth= -nifi.security.authorizedUsers.file=./target/conf/authorized-users.xml -nifi.security.user.credential.cache.duration=24 hours -nifi.security.user.authority.provider=nifi.authorization.FileAuthorizationProvider -nifi.security.support.new.account.requests= -nifi.security.default.user.roles= +nifi.security.user.authorizer= # cluster common properties (cluster manager and nodes must have same values) # nifi.cluster.protocol.heartbeat.interval=5 sec diff --git a/nifi-docs/src/main/asciidoc/administration-guide.adoc b/nifi-docs/src/main/asciidoc/administration-guide.adoc index 86c340adb5..8d784c6937 100644 --- a/nifi-docs/src/main/asciidoc/administration-guide.adoc +++ b/nifi-docs/src/main/asciidoc/administration-guide.adoc @@ -154,9 +154,6 @@ NiFi provides several different configuration options for security purposes. The by the NiFi cluster protocol. If the Truststore properties are not set, this must be `false`. Otherwise, a value of `true` indicates that nodes in the cluster will be authenticated and must have certificates that are trusted by the Truststores. -|`nifi.security.anonymous.authorities` | Specifies the roles that should be granted to users that connect over HTTPS anonymously. All users can make - use of anonymous access, however if they have been granted a particular level of access by an administrator - it will take precedence if they access NiFi using a client certificate or once they have logged in. |================================================================================================================================================== Once the above properties have been configured, we can enable the User Interface to be accessed over HTTPS instead of HTTP. This is accomplished @@ -167,10 +164,10 @@ be accessible from all network interfaces, a value of `0.0.0.0` should be used. NOTE: It is important when enabling HTTPS that the `nifi.web.http.port` property be unset. Similar to `nifi.security.needClientAuth`, the web server can be configured to require certificate based client authentication for users accessing -the User Interface. In order to do this it must be configured to not support username/password authentication (see below) and not grant access to -anonymous users (see `nifi.security.anonymous.authorities` above). Either of these options will configure the web server to WANT certificate based client -authentication. This will allow it to support users with certificates and those without that may be logging in with their credentials or those accessing -anonymously. If username/password authentication and anonymous access are not configured, the web server will REQUIRE certificate based client authentication. +the User Interface. In order to do this it must be configured to not support username/password authentication (see below). Either of these options +will configure the web server to WANT certificate based client authentication. This will allow it to support users with certificates and those without +that may be logging in with their credentials or those accessing anonymously. If username/password authentication and anonymous access are not configured, +the web server will REQUIRE certificate based client authentication. Now that the User Interface has been secured, we can easily secure Site-to-Site connections and inner-cluster communications, as well. This is accomplished by setting the `nifi.remote.input.secure` and `nifi.cluster.protocol.is.secure` properties, respectively, to `true`. @@ -289,127 +286,6 @@ nifi.security.user.login.identity.provider=kerberos-provider See also <> to allow single sign-on access via client Kerberos tickets. -Controlling Levels of Access ----------------------------- - -Once NiFi is configured to run securely and an authentication mechanism is configured, it is necessary -to configure who will have access to the system and what types of access those people will have. -NiFi controls this through the user of an 'Authority Provider.' The Authority Provider is a pluggable -mechanism for providing authorizations to different users. Which Authority Provider to use is configured -using two properties in the _nifi.properties_ file. - -The `nifi.authority.provider.configuration.file` property specifies the configuration file for Authority Providers. -The `nifi.security.user.authority.provider` property indicates which of the configured Authority Providers should be -used. - -By default, the `file-provider` Authority Provider is selected and is configured to use the permissions granted in -the _authorized-users.xml_ file. This is typically sufficient for instances of NiFi that are run in "standalone" mode. -If the NiFi instance is configured to run in a cluster, the node will typically use the `cluster-node-provider` -Provider and the Cluster Manager will typically use the `cluster-ncm-provider` Provider. Both of these Providers -have a default configuration in the _authority-providers.xml_ file but are commented out. - -When using the `cluster-node-provider` Provider, all of the authorization is provided by the Cluster Manager. In this -way, the configuration only has to be maintained in one place and will be consistent across the entire cluster. - -When configuring the Cluster Manager or a standalone node, it is necessary to manually designate an ADMIN user -in the _authorized-users.xml_ file, which is located in the root installation's conf directory. -After this ADMIN user has been added, s/he may grant access -to other users, systems, and other instances of NiFi, through the User Interface (UI) without having to manually edit the _authorized-users.xml_ -file. If you are the administrator, you would add yourself as the ADMIN user in this file. - -Open the _authorized-users.xml_ file in a text editor. You will notice that it includes a template -to guide you, with example entries that are commented out. - -It is only necessary to manually add one user, the ADMIN user, to this file. -So, at a minimum, the following example entry should be included and contain the user Distinguished Name (DN) -in place of "user dn - read only and admin": - ----- - - - - - ----- - -Here is an LDAP example entry using the name John Smith: - ----- - - - - - ----- - -Here is a Kerberos example entry using the name John Smith and realm `NIFI.APACHE.ORG`: - ----- - - - - - ----- - -After the _authorized-users.xml_ file has been edited and saved, restart NiFi. -Once the application starts, the ADMIN user is -able to access the UI at the HTTPS URL that is configured in the _nifi.properties_ file. - -From the UI, click on the Users icon ( image:iconUsers.png["Users", width=32] ) in the -Management Toolbar (upper-right corner of the UI), and the User Management Page opens. - -The ADMIN user should be listed. Click on the pencil icon to see this user's role(s). You may edit the -roles by selecting the appropriate checkboxes. - -The following roles are available in NiFi: - -[options="header,footer"] -|======================================================================================================== -| Role Name | Description -| Administrator | Administrator is able to configure thread pool sizes and user accounts as well as - purge the dataflow change history. -| Data Flow Manager | Data Flow Manager is given the ability to manipulate the dataflow. S/he is able to - add, remove, and manipulate components on the graph; add, remove, and manipulate - Controller Services and Reporting Tasks; create and manage templates; - view statistics; and view the bulletin board. -| Read Only | Users with Read Only access are able to view the dataflow but are unable to change anything. -| Provenance | Users with Provenance access are able to query the Data Provenance repository and view - the lineage of data. Additionally, this role provides the ability to view or download - the content of a FlowFile from a Provenance event (assuming that the content is still - available in the Content Repository and that the Authority Provider also grants access). - This access is not provided to users with Read Only - (unless the user has both Read Only and Provenance roles) because the information provided - to users with this role can potentially be very sensitive in nature, as all FlowFile attributes - and data are exposed. In order to Replay a Provenance event, a user is required to have both - the Provenance role as well as the Data Flow Manager role. -| NiFi | The NiFi Role is intended to be assigned to machines that will interact with an instance of NiFi - via Site-to-Site. This role provides the ability to send data to or retrieve data from Root - Group Ports (but only those that they are given permissions to interact with - see the User Guide - for more information on providing access to specific Ports) as well as obtain information about - which Ports exist. Note that this role allows the client to know only about the Ports that it - has permissions to interact with. -| Proxy | The Proxy Role is assigned to a system in order to grant that system permission to make requests - on behalf of a user. For instance, if an HTTP proxy service is used to gain access to the system, - the certificate being used by that service can be given the Proxy Role. -|======================================================================================================== - - -When users want access to the NiFi UI, they navigate to the configured URL and are -prompted to request access. When someone has requested access, the ADMIN user sees a star -on the Users icon in the Management Toolbar, alerting the ADMIN to the fact that a request is -pending. Upon opening the User Management Page, the pending request is visible, and the ADMIN -can grant access and click on the pencil icon to set the user's roles appropriately. - -The ADMIN may also select multiple users and add them to a "Group". Hold down the Shift key and select -multiple users, then click the `Group` button in the upper-right corner of the User Management Page. -Then, provide a name for the group. - -The group feature is especially useful when a remote NiFi cluster is connecting to this NiFi using -a Remote Process Group. In that scenario, all the nodes -in the remote cluster can be included in the same group. When the ADMIN wants to grant port access to the remote -cluster, s/he can grant it to the group and avoid having to grant it individually to each node in the cluster. - [[encryption]] Encryption Configuration ------------------------ @@ -1454,15 +1330,8 @@ Security Configuration section of this Administrator's Guide. |nifi.security.truststoreType|The truststore type. It is blank by default. |nifi.security.truststorePasswd|The truststore password. It is blank by default. |nifi.security.needClientAuth|This indicates whether client authentication in the cluster protocol. It is blank by default. -|nifi.security.user.credential.cache.duration|The length of time to cache user credentials. The default value is 24 hours. -|nifi.security.user.authority.provider|This indicates what type of authority provider to use. The default value is file-provider, which refers to the file -configured in the core property `nifi.authority.provider.configuration.file`. Another authority provider may be used, such as when the NiFi instance is part of a cluster. But the default value of file-provider is fine for a standalone instance of NiFi. |nifi.security.user.login.identity.provider|This indicates what type of login identity provider to use. The default value is blank, can be set to the identifier from a provider in the file specified in `nifi.login.identity.provider.configuration.file`. Setting this property will trigger NiFi to support username/password authentication. -|nifi.security.support.new.account.requests|This indicates whether a secure NiFi is configured to allow users to request access. It is blank by default. -|nifi.security.anonymous.authorities|This indicates what roles to grant to anonymous users accessing NiFi over HTTPS. It is blank by default, but could be -set to any combination of ROLE_MONITOR, ROLE_DFM, ROLE_ADMIN, ROLE_PROVENANCE, ROLE_NIFI. Leaving this property blank will require that users accessing NiFi -over HTTPS be authenticated either using a client certificate or their credentials against the configured log identity provider. |nifi.security.ocsp.responder.url|This is the URL for the Online Certificate Status Protocol (OCSP) responder if one is being used. It is blank by default. |nifi.security.ocsp.responder.certificate|This is the location of the OCSP responder certificate if one is being used. It is blank by default. |==== diff --git a/nifi-nar-bundles/nifi-cassandra-bundle/nifi-cassandra-processors/src/main/java/org/apache/nifi/processors/cassandra/AbstractCassandraProcessor.java b/nifi-nar-bundles/nifi-cassandra-bundle/nifi-cassandra-processors/src/main/java/org/apache/nifi/processors/cassandra/AbstractCassandraProcessor.java index 672a3eedcc..478ffaf8dc 100644 --- a/nifi-nar-bundles/nifi-cassandra-bundle/nifi-cassandra-processors/src/main/java/org/apache/nifi/processors/cassandra/AbstractCassandraProcessor.java +++ b/nifi-nar-bundles/nifi-cassandra-bundle/nifi-cassandra-processors/src/main/java/org/apache/nifi/processors/cassandra/AbstractCassandraProcessor.java @@ -26,7 +26,7 @@ import com.datastax.driver.core.Session; import org.apache.avro.Schema; import org.apache.avro.SchemaBuilder; import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.authorization.exception.ProviderCreationException; +import org.apache.nifi.authentication.exception.ProviderCreationException; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.components.PropertyValue; import org.apache.nifi.components.ValidationContext; diff --git a/nifi-nar-bundles/nifi-cassandra-bundle/nifi-cassandra-processors/src/test/java/org/apache/nifi/processors/cassandra/AbstractCassandraProcessorTest.java b/nifi-nar-bundles/nifi-cassandra-bundle/nifi-cassandra-processors/src/test/java/org/apache/nifi/processors/cassandra/AbstractCassandraProcessorTest.java index 1f62997dcf..19e23203fa 100644 --- a/nifi-nar-bundles/nifi-cassandra-bundle/nifi-cassandra-processors/src/test/java/org/apache/nifi/processors/cassandra/AbstractCassandraProcessorTest.java +++ b/nifi-nar-bundles/nifi-cassandra-bundle/nifi-cassandra-processors/src/test/java/org/apache/nifi/processors/cassandra/AbstractCassandraProcessorTest.java @@ -22,7 +22,7 @@ import com.datastax.driver.core.DataType; import com.datastax.driver.core.Metadata; import com.datastax.driver.core.Row; import com.google.common.collect.Sets; -import org.apache.nifi.authorization.exception.ProviderCreationException; +import org.apache.nifi.authentication.exception.ProviderCreationException; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework-nar/pom.xml b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework-nar/pom.xml index dca1d97ad4..bd8272a2f6 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework-nar/pom.xml +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework-nar/pom.xml @@ -31,14 +31,6 @@ org.apache.nifi nifi-jetty - - org.apache.nifi - nifi-cluster-authorization-provider - - - org.apache.nifi - nifi-file-authorization-provider - diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/KeyDataSourceFactoryBean.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/KeyDataSourceFactoryBean.java new file mode 100644 index 0000000000..83479532c0 --- /dev/null +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/KeyDataSourceFactoryBean.java @@ -0,0 +1,147 @@ +/* + * 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. + */ +package org.apache.nifi.admin; + +import org.apache.commons.lang3.StringUtils; +import org.apache.nifi.util.NiFiProperties; +import org.h2.jdbcx.JdbcConnectionPool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.FactoryBean; + +import java.io.File; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +public class KeyDataSourceFactoryBean implements FactoryBean { + + private static final Logger logger = LoggerFactory.getLogger(KeyDataSourceFactoryBean.class); + private static final String NF_USERNAME_PASSWORD = "nf"; + private static final int MAX_CONNECTIONS = 5; + + // database file name + private static final String USER_KEYS_DATABASE_FILE_NAME = "nifi-user-keys"; + + // ---------- + // keys table + // ---------- + + private static final String CREATE_KEY_TABLE = "CREATE TABLE KEY (" + + "ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " + + "IDENTITY VARCHAR2(4096) NOT NULL UNIQUE, " + + "KEY VARCHAR2(100) NOT NULL" + + ")"; + + private JdbcConnectionPool connectionPool; + + private NiFiProperties properties; + + @Override + public Object getObject() throws Exception { + if (connectionPool == null) { + + // locate the repository directory + String repositoryDirectoryPath = properties.getProperty(NiFiProperties.REPOSITORY_DATABASE_DIRECTORY); + + // ensure the repository directory is specified + if (repositoryDirectoryPath == null) { + throw new NullPointerException("Database directory must be specified."); + } + + // create a handle to the repository directory + File repositoryDirectory = new File(repositoryDirectoryPath); + + // create a handle to the database directory and file + File databaseFile = new File(repositoryDirectory, USER_KEYS_DATABASE_FILE_NAME); + String databaseUrl = getDatabaseUrl(databaseFile); + + // create the pool + connectionPool = JdbcConnectionPool.create(databaseUrl, NF_USERNAME_PASSWORD, NF_USERNAME_PASSWORD); + connectionPool.setMaxConnections(MAX_CONNECTIONS); + + Connection connection = null; + ResultSet rs = null; + Statement statement = null; + try { + // get a connection + connection = connectionPool.getConnection(); + connection.setAutoCommit(false); + + // create a statement for creating/updating the database + statement = connection.createStatement(); + + // determine if the key table need to be created + rs = connection.getMetaData().getTables(null, null, "KEY", null); + if (!rs.next()) { + statement.execute(CREATE_KEY_TABLE); + } + + // commit any changes + connection.commit(); + } catch (SQLException sqle) { + RepositoryUtils.rollback(connection, logger); + throw sqle; + } finally { + RepositoryUtils.closeQuietly(rs); + RepositoryUtils.closeQuietly(statement); + RepositoryUtils.closeQuietly(connection); + } + } + + return connectionPool; + } + + private String getDatabaseUrl(File databaseFile) { + String databaseUrl = "jdbc:h2:" + databaseFile + ";AUTOCOMMIT=OFF;DB_CLOSE_ON_EXIT=FALSE;LOCK_MODE=3"; + String databaseUrlAppend = properties.getProperty(NiFiProperties.H2_URL_APPEND); + if (StringUtils.isNotBlank(databaseUrlAppend)) { + databaseUrl += databaseUrlAppend; + } + return databaseUrl; + } + + @Override + public Class getObjectType() { + return JdbcConnectionPool.class; + } + + @Override + public boolean isSingleton() { + return true; + } + + public void setProperties(NiFiProperties properties) { + this.properties = properties; + } + + public void shutdown() { + // shutdown the connection pool + if (connectionPool != null) { + try { + connectionPool.dispose(); + } catch (Exception e) { + logger.warn("Unable to dispose of connection pool: " + e.getMessage()); + if (logger.isDebugEnabled()) { + logger.warn(StringUtils.EMPTY, e); + } + } + } + } + +} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/UserDataSourceFactoryBean.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/UserDataSourceFactoryBean.java deleted file mode 100644 index d45719d433..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/UserDataSourceFactoryBean.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin; - -import java.io.File; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; -import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.authorization.Authority; -import org.h2.jdbcx.JdbcConnectionPool; -import org.apache.nifi.user.NiFiUser; -import org.apache.nifi.util.NiFiProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.FactoryBean; - -public class UserDataSourceFactoryBean implements FactoryBean { - - private static final Logger logger = LoggerFactory.getLogger(UserDataSourceFactoryBean.class); - private static final String NF_USERNAME_PASSWORD = "nf"; - private static final int MAX_CONNECTIONS = 5; - - // database file name - private static final String AUDIT_DATABASE_FILE_NAME = "nifi-users"; - - private static final String CREATE_USER_TABLE = "CREATE TABLE USER (" - + "ID VARCHAR2(100) NOT NULL PRIMARY KEY, " - + "IDENTITY VARCHAR2(4096) NOT NULL UNIQUE, " - + "USER_NAME VARCHAR2(4096) NOT NULL, " - + "USER_GROUP VARCHAR2(100), " - + "CREATION TIMESTAMP NOT NULL, " - + "LAST_ACCESSED TIMESTAMP, " - + "LAST_VERIFIED TIMESTAMP, " - + "JUSTIFICATION VARCHAR2(500) NOT NULL, " - + "STATUS VARCHAR2(10) NOT NULL" - + ")"; - - private static final String CREATE_AUTHORITY_TABLE = "CREATE TABLE AUTHORITY (" - + "ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " - + "USER_ID VARCHAR2(100) NOT NULL, " - + "ROLE VARCHAR2(50) NOT NULL, " - + "FOREIGN KEY (USER_ID) REFERENCES USER (ID), " - + "CONSTRAINT USER_ROLE_UNIQUE_CONSTRAINT UNIQUE (USER_ID, ROLE)" - + ")"; - - private static final String INSERT_ANONYMOUS_USER = "INSERT INTO USER (" - + "ID, IDENTITY, USER_NAME, CREATION, LAST_VERIFIED, JUSTIFICATION, STATUS" - + ") VALUES (" - + "'" + UUID.randomUUID().toString() + "', " - + "'" + NiFiUser.ANONYMOUS_USER_IDENTITY + "', " - + "'" + NiFiUser.ANONYMOUS_USER_IDENTITY + "', " - + "NOW(), " - + "NOW(), " - + "'Anonymous user needs no justification', " - + "'ACTIVE'" - + ")"; - - private static final String INSERT_ANONYMOUS_AUTHORITY = "INSERT INTO AUTHORITY (" - + "USER_ID, ROLE" - + ") VALUES (" - + "(SELECT ID FROM USER WHERE IDENTITY = '" + NiFiUser.ANONYMOUS_USER_IDENTITY + "'), " - + "'%s'" - + ")"; - - private static final String DELETE_ANONYMOUS_AUTHORITIES = "DELETE FROM AUTHORITY " - + "WHERE USER_ID = (SELECT ID FROM USER WHERE IDENTITY = '" + NiFiUser.ANONYMOUS_USER_IDENTITY + "')"; - - private static final String RENAME_DN_COLUMN = "ALTER TABLE USER ALTER COLUMN DN RENAME TO IDENTITY"; - private static final String RESIZE_IDENTITY_COLUMN = "ALTER TABLE USER MODIFY IDENTITY VARCHAR(4096)"; - private static final String RESIZE_USER_NAME_COLUMN = "ALTER TABLE USER MODIFY USER_NAME VARCHAR(4096)"; - - // ---------- - // keys table - // ---------- - private static final String CREATE_KEY_TABLE = "CREATE TABLE KEY (" - + "ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " - + "IDENTITY VARCHAR2(4096) NOT NULL UNIQUE, " - + "KEY VARCHAR2(100) NOT NULL" - + ")"; - - private JdbcConnectionPool connectionPool; - - private NiFiProperties properties; - - @Override - public Object getObject() throws Exception { - if (connectionPool == null) { - - // locate the repository directory - String repositoryDirectoryPath = properties.getProperty(NiFiProperties.REPOSITORY_DATABASE_DIRECTORY); - - // ensure the repository directory is specified - if (repositoryDirectoryPath == null) { - throw new NullPointerException("Database directory must be specified."); - } - - // get the roles being granted to anonymous users - final Set rawAnonymousAuthorities = new HashSet<>(properties.getAnonymousAuthorities()); - final Set anonymousAuthorities = Authority.convertRawAuthorities(rawAnonymousAuthorities); - - // ensure every authorities was recognized - if (rawAnonymousAuthorities.size() != anonymousAuthorities.size()) { - final Set validAuthorities = Authority.convertAuthorities(anonymousAuthorities); - rawAnonymousAuthorities.removeAll(validAuthorities); - throw new IllegalStateException(String.format("Invalid authorities specified for anonymous access: [%s]. Valid values are: [%s].", - StringUtils.join(rawAnonymousAuthorities, ", "), StringUtils.join(Authority.values(), ", "))); - } - - // create a handle to the repository directory - File repositoryDirectory = new File(repositoryDirectoryPath); - - // create a handle to the database directory and file - File databaseFile = new File(repositoryDirectory, AUDIT_DATABASE_FILE_NAME); - String databaseUrl = getDatabaseUrl(databaseFile); - - // create the pool - connectionPool = JdbcConnectionPool.create(databaseUrl, NF_USERNAME_PASSWORD, NF_USERNAME_PASSWORD); - connectionPool.setMaxConnections(MAX_CONNECTIONS); - - Connection connection = null; - ResultSet rs = null; - Statement statement = null; - try { - // get a connection - connection = connectionPool.getConnection(); - connection.setAutoCommit(false); - - // create a statement for creating/updating the database - statement = connection.createStatement(); - - // determine if the tables need to be created - rs = connection.getMetaData().getTables(null, null, "USER", null); - if (!rs.next()) { - logger.info("Database not built for repository: " + databaseUrl + ". Building now..."); - - // create the tables - statement.execute(CREATE_USER_TABLE); - statement.execute(CREATE_AUTHORITY_TABLE); - - // seed the anonymous user - statement.execute(INSERT_ANONYMOUS_USER); - } else { - logger.info("Existing database found and connected to at: " + databaseUrl); - RepositoryUtils.closeQuietly(rs); - - // if the DN column exists, transform the table - rs = connection.getMetaData().getColumns(null, null, "USER", "DN"); - if (rs.next()) { - statement.execute(RENAME_DN_COLUMN); - statement.execute(RESIZE_IDENTITY_COLUMN); - statement.execute(RESIZE_USER_NAME_COLUMN); - } - - // remove all authorities for the anonymous user - statement.execute(DELETE_ANONYMOUS_AUTHORITIES); - } - - // add all authorities for the anonymous user - for (final Authority authority : anonymousAuthorities) { - statement.execute(String.format(INSERT_ANONYMOUS_AUTHORITY, authority.name())); - } - - RepositoryUtils.closeQuietly(rs); - - // determine if the key table need to be created - rs = connection.getMetaData().getTables(null, null, "KEY", null); - if (!rs.next()) { - statement.execute(CREATE_KEY_TABLE); - } - - // commit any changes - connection.commit(); - } catch (SQLException sqle) { - RepositoryUtils.rollback(connection, logger); - throw sqle; - } finally { - RepositoryUtils.closeQuietly(rs); - RepositoryUtils.closeQuietly(statement); - RepositoryUtils.closeQuietly(connection); - } - } - - return connectionPool; - } - - private String getDatabaseUrl(File databaseFile) { - String databaseUrl = "jdbc:h2:" + databaseFile + ";AUTOCOMMIT=OFF;DB_CLOSE_ON_EXIT=FALSE;LOCK_MODE=3"; - String databaseUrlAppend = properties.getProperty(NiFiProperties.H2_URL_APPEND); - if (StringUtils.isNotBlank(databaseUrlAppend)) { - databaseUrl += databaseUrlAppend; - } - return databaseUrl; - } - - @Override - public Class getObjectType() { - return JdbcConnectionPool.class; - } - - @Override - public boolean isSingleton() { - return true; - } - - public void setProperties(NiFiProperties properties) { - this.properties = properties; - } - - public void shutdown() { - - // shutdown the connection pool - if (connectionPool != null) { - try { - connectionPool.dispose(); - } catch (Exception e) { - logger.warn("Unable to dispose of connection pool: " + e.getMessage()); - if (logger.isDebugEnabled()) { - logger.warn(StringUtils.EMPTY, e); - } - } - } - - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/AuthorityDAO.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/AuthorityDAO.java deleted file mode 100644 index b80b78ed63..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/AuthorityDAO.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.dao; - -import java.util.Set; -import org.apache.nifi.authorization.Authority; - -/** - * Authority data access. - */ -public interface AuthorityDAO { - - /** - * Finds all Authority for the specified user. - * - * @param userId identifier of user - * @return authorities - */ - Set findAuthoritiesByUserId(String userId) throws DataAccessException; - - /** - * Creates new Authorities for the specified user in addition to authorities - * they already have. - * - * @param authorities to add to the given user - * @param userId identifier of user - */ - void createAuthorities(Set authorities, String userId) throws DataAccessException; - - /** - * Removes all Authorities for the specified user. - * - * @param userId user identifier - * @throws DataAccessException if unable to access authorities - */ - void deleteAuthorities(String userId) throws DataAccessException; - - /** - * Removes the specified Authority. - * - * @param authorities to remove - * @param userId user id - */ - void deleteAuthorities(Set authorities, String userId) throws DataAccessException; -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/DAOFactory.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/DAOFactory.java index eb7e3ce6a9..3fcc6d835a 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/DAOFactory.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/DAOFactory.java @@ -21,11 +21,7 @@ package org.apache.nifi.admin.dao; */ public interface DAOFactory { - UserDAO getUserDAO(); - ActionDAO getActionDAO(); - AuthorityDAO getAuthorityDAO(); - KeyDAO getKeyDAO(); } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/UserDAO.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/UserDAO.java deleted file mode 100644 index 7e91c07074..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/UserDAO.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.dao; - -import java.util.Date; -import java.util.Set; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; - -/** - * Defines the user data access object. - */ -public interface UserDAO { - - /** - * Determines whether there are any PENDING user accounts. - * - * @return true if pending - * @throws DataAccessException dae - */ - Boolean hasPendingUserAccounts() throws DataAccessException; - - /** - * Returns all users. - * - * @return all users - * @throws DataAccessException dae - */ - Set findUsers() throws DataAccessException; - - /** - * Returns all user groups. - * - * @return all group names - * @throws DataAccessException dae - */ - Set findUserGroups() throws DataAccessException; - - /** - * Returns all users for the specified group. - * - * @param group group - * @return users in group - * @throws DataAccessException dae - */ - Set findUsersForGroup(String group) throws DataAccessException; - - /** - * Returns the user with the specified id. - * - * @param id user id - * @return user for the given id - * @throws DataAccessException dae - */ - NiFiUser findUserById(String id) throws DataAccessException; - - /** - * Returns the user with the specified DN. - * - * @param dn user dn - * @return user - */ - NiFiUser findUserByDn(String dn) throws DataAccessException; - - /** - * Creates a new user based off the specified NiFiUser. - * - * @param user to create - * @return the created user with it's id - */ - NiFiUser createUser(NiFiUser user) throws DataAccessException; - - /** - * Updates the specified NiFiUser. - * - * @param user to update - */ - void updateUser(NiFiUser user) throws DataAccessException; - - /** - * Deletes the specified user. - * - * @param id user identifier - * @throws DataAccessException dae - */ - void deleteUser(String id) throws DataAccessException; - - /** - * Sets the status of the specified group. - * - * @param group group - * @param status status - * @throws DataAccessException dae - */ - void updateGroupStatus(String group, AccountStatus status) throws DataAccessException; - - /** - * Sets the last verified time for all users in the specified group. - * - * @param group group - * @param lastVerified date last verified - * @throws DataAccessException dae - */ - void updateGroupVerification(String group, Date lastVerified) throws DataAccessException; - - /** - * Ungroups the specified group. - * - * @param group to ungroup - * @throws DataAccessException dae - */ - void ungroup(String group) throws DataAccessException; - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/DAOFactoryImpl.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/DAOFactoryImpl.java index 940e364230..09ad1038ad 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/DAOFactoryImpl.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/DAOFactoryImpl.java @@ -18,10 +18,8 @@ package org.apache.nifi.admin.dao.impl; import java.sql.Connection; import org.apache.nifi.admin.dao.ActionDAO; -import org.apache.nifi.admin.dao.AuthorityDAO; import org.apache.nifi.admin.dao.DAOFactory; import org.apache.nifi.admin.dao.KeyDAO; -import org.apache.nifi.admin.dao.UserDAO; /** * @@ -39,16 +37,6 @@ public class DAOFactoryImpl implements DAOFactory { return new StandardActionDAO(connection); } - @Override - public AuthorityDAO getAuthorityDAO() { - return new StandardAuthorityDAO(connection); - } - - @Override - public UserDAO getUserDAO() { - return new StandardUserDAO(connection); - } - @Override public KeyDAO getKeyDAO() { return new StandardKeyDAO(connection); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/StandardAuthorityDAO.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/StandardAuthorityDAO.java deleted file mode 100644 index 4e2cc26db5..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/StandardAuthorityDAO.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.dao.impl; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.EnumSet; -import java.util.Set; -import org.apache.nifi.admin.RepositoryUtils; -import org.apache.nifi.admin.dao.AuthorityDAO; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.authorization.Authority; - -/** - * - */ -public class StandardAuthorityDAO implements AuthorityDAO { - - private static final String SELECT_AUTHORITIES_FOR_USER = "SELECT ID, ROLE " - + "FROM AUTHORITY " - + "WHERE USER_ID = ?"; - - private static final String INSERT_AUTHORITY = "INSERT INTO AUTHORITY (" - + "USER_ID, ROLE" - + ") VALUES (" - + "?, ?" - + ")"; - - private static final String DELETE_AUTHORITY = "DELETE FROM AUTHORITY " - + "WHERE USER_ID = ? AND ROLE = ?"; - - private static final String DELETE_AUTHORITIES_FOR_USER = "DELETE FROM AUTHORITY " - + "WHERE USER_ID = ?"; - - private final Connection connection; - - public StandardAuthorityDAO(Connection connection) { - this.connection = connection; - } - - @Override - public void createAuthorities(Set authorities, String userId) throws DataAccessException { - if (authorities == null) { - throw new IllegalArgumentException("Specified authorities cannot be null."); - } - - // ensure there are some authorities to create - if (!authorities.isEmpty()) { - PreparedStatement statement = null; - try { - // add each authority for the specified user - statement = connection.prepareStatement(INSERT_AUTHORITY); - statement.setString(1, userId); - for (Authority authority : authorities) { - statement.setString(2, authority.toString()); - statement.addBatch(); - } - - // insert the authorities - int[] updateCounts = statement.executeBatch(); - for (int updateCount : updateCounts) { - if (updateCount != 1) { - throw new DataAccessException("Unable to insert user authorities."); - } - } - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } catch (DataAccessException dae) { - throw dae; - } finally { - RepositoryUtils.closeQuietly(statement); - } - } - } - - @Override - public void deleteAuthorities(String userId) throws DataAccessException { - // ensure there are some authorities to create - PreparedStatement statement = null; - try { - // add each authority for the specified user - statement = connection.prepareStatement(DELETE_AUTHORITIES_FOR_USER); - statement.setString(1, userId); - - // insert the authorities - statement.executeUpdate(); - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } finally { - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public void deleteAuthorities(Set authorities, String userId) throws DataAccessException { - if (authorities == null) { - throw new IllegalArgumentException("Specified authorities cannot be null."); - } - - // ensure there are some authorities to create - if (!authorities.isEmpty()) { - PreparedStatement statement = null; - try { - // add each authority for the specified user - statement = connection.prepareStatement(DELETE_AUTHORITY); - statement.setString(1, userId); - for (Authority authority : authorities) { - statement.setString(2, authority.toString()); - statement.addBatch(); - } - - // insert the authorities - int[] updateCounts = statement.executeBatch(); - for (int updateCount : updateCounts) { - if (updateCount != 1) { - throw new DataAccessException("Unable to remove user authorities."); - } - } - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } catch (DataAccessException dae) { - throw dae; - } finally { - RepositoryUtils.closeQuietly(statement); - } - } - } - - @Override - public Set findAuthoritiesByUserId(String userId) throws DataAccessException { - Set authorities = EnumSet.noneOf(Authority.class); - PreparedStatement statement = null; - ResultSet rs = null; - try { - // add each authority for the specified user - statement = connection.prepareStatement(SELECT_AUTHORITIES_FOR_USER); - statement.setString(1, userId); - - // execute the query - rs = statement.executeQuery(); - - // create each corresponding authority - while (rs.next()) { - authorities.add(Authority.valueOfAuthority(rs.getString("ROLE"))); - } - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } finally { - RepositoryUtils.closeQuietly(rs); - RepositoryUtils.closeQuietly(statement); - } - - return authorities; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/StandardUserDAO.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/StandardUserDAO.java deleted file mode 100644 index 20356e32f0..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/StandardUserDAO.java +++ /dev/null @@ -1,641 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.dao.impl; - -import java.nio.charset.StandardCharsets; -import java.sql.Connection; -import org.apache.nifi.admin.dao.UserDAO; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Types; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; -import org.apache.nifi.admin.RepositoryUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; - -/** - * Responsible for loading and persisting NiFiUsers. - */ -public class StandardUserDAO implements UserDAO { - - private static final String SELECT_PENDING_ACCOUNTS_COUNT = "SELECT " - + "COUNT(*) as PENDING_ACCOUNTS " - + "FROM USER U " - + "WHERE U.STATUS = 'PENDING'"; - - private static final String SELECT_USER_BY_USER = "SELECT " - + "U.ID, " - + "U.IDENTITY, " - + "U.USER_NAME, " - + "U.USER_GROUP, " - + "U.CREATION, " - + "U.LAST_ACCESSED, " - + "U.LAST_VERIFIED, " - + "U.JUSTIFICATION, " - + "U.STATUS, " - + "A.ROLE " - + "FROM USER U " - + "LEFT JOIN AUTHORITY A " // ensures that users without authorities are still matched - + "ON U.ID = A.USER_ID " - + "WHERE U.IDENTITY = ?"; - - private static final String SELECT_USER_BY_ID = "SELECT " - + "U.ID, " - + "U.IDENTITY, " - + "U.USER_NAME, " - + "U.USER_GROUP, " - + "U.CREATION, " - + "U.LAST_ACCESSED, " - + "U.LAST_VERIFIED, " - + "U.JUSTIFICATION, " - + "U.STATUS, " - + "A.ROLE " - + "FROM USER U " - + "LEFT JOIN AUTHORITY A " // ensures that users without authorities are still matched - + "ON U.ID = A.USER_ID " - + "WHERE U.ID = ?"; - - private static final String SELECT_USERS = "SELECT " - + "U.ID, " - + "U.IDENTITY, " - + "U.USER_NAME, " - + "U.USER_GROUP, " - + "U.CREATION, " - + "U.LAST_ACCESSED, " - + "U.LAST_VERIFIED, " - + "U.JUSTIFICATION, " - + "U.STATUS, " - + "A.ROLE " - + "FROM USER U " - + "LEFT JOIN AUTHORITY A " // ensures that users without authorities are still matched - + "ON U.ID = A.USER_ID " - + "WHERE U.IDENTITY <> ?"; - - private static final String SELECT_USER_GROUPS = "SELECT DISTINCT " - + "U.USER_GROUP " - + "FROM USER U"; - - private static final String SELECT_USER_GROUP = "SELECT " - + "U.ID, " - + "U.IDENTITY, " - + "U.USER_NAME, " - + "U.USER_GROUP, " - + "U.CREATION, " - + "U.LAST_ACCESSED, " - + "U.LAST_VERIFIED, " - + "U.JUSTIFICATION, " - + "U.STATUS, " - + "A.ROLE " - + "FROM USER U " - + "LEFT JOIN AUTHORITY A " // ensures that users without authorities are still matched - + "ON U.ID = A.USER_ID " - + "WHERE U.IDENTITY <> ? AND U.USER_GROUP = ?"; - - private static final String INSERT_USER = "INSERT INTO USER (" - + "ID, IDENTITY, USER_NAME, USER_GROUP, CREATION, LAST_VERIFIED, JUSTIFICATION, STATUS" - + ") VALUES (" - + "?, " - + "?, " - + "?, " - + "?, " - + "NOW(), " - + "?, " - + "?, " - + "?" - + ")"; - - private static final String UPDATE_USER = "UPDATE USER SET " - + "IDENTITY = ?, " - + "USER_NAME = ?, " - + "USER_GROUP = ?, " - + "LAST_ACCESSED = ?, " - + "LAST_VERIFIED = ?, " - + "JUSTIFICATION = ?, " - + "STATUS = ? " - + "WHERE ID = ?"; - - private static final String UPDATE_USER_GROUP_STATUS = "UPDATE USER SET " - + "STATUS = ?," - + "USER_GROUP = NULL " - + "WHERE USER_GROUP = ?"; - - private static final String UPDATE_USER_GROUP_VERIFICATION = "UPDATE USER SET " - + "LAST_VERIFIED = ? " - + "WHERE USER_GROUP = ?"; - - private static final String UNGROUP_GROUP = "UPDATE USER SET " - + "USER_GROUP = NULL " - + "WHERE USER_GROUP = ?"; - - private static final String DELETE_USER = "DELETE FROM USER " - + "WHERE ID = ?"; - - private final Connection connection; - - public StandardUserDAO(Connection connection) { - this.connection = connection; - } - - @Override - public Boolean hasPendingUserAccounts() throws DataAccessException { - PreparedStatement statement = null; - ResultSet rs = null; - try { - // create the connection and obtain a statement - statement = connection.prepareStatement(SELECT_PENDING_ACCOUNTS_COUNT); - - // execute the query - rs = statement.executeQuery(); - - // get the first row which will contain the number of pending accounts - if (rs.next()) { - int pendingAccounts = rs.getInt("PENDING_ACCOUNTS"); - return pendingAccounts > 0; - } - - // query returned no results? - return false; - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } finally { - RepositoryUtils.closeQuietly(rs); - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public Set findUsers() throws DataAccessException { - Set users = new HashSet<>(); - - PreparedStatement statement = null; - ResultSet rs = null; - try { - // create the connection and obtain a statement - statement = connection.prepareStatement(SELECT_USERS); - statement.setString(1, NiFiUser.ANONYMOUS_USER_IDENTITY); - - // execute the query - rs = statement.executeQuery(); - - // create the user - NiFiUser user = null; - - // go through the user and its roles - while (rs.next()) { - // get the user id for the current record - String userId = rs.getString("ID"); - - // create the user during the first iteration - if (user == null || !userId.equals(user.getId())) { - user = new NiFiUser(); - user.setId(userId); - user.setIdentity(rs.getString("IDENTITY")); - user.setUserName(rs.getString("USER_NAME")); - user.setUserGroup(rs.getString("USER_GROUP")); - user.setJustification(rs.getString("JUSTIFICATION")); - user.setStatus(AccountStatus.valueOfStatus(rs.getString("STATUS"))); - - // set the creation date - user.setCreation(new Date(rs.getTimestamp("CREATION").getTime())); - - // get the last accessed date - if (rs.getTimestamp("LAST_ACCESSED") != null) { - user.setLastAccessed(new Date(rs.getTimestamp("LAST_ACCESSED").getTime())); - } - - // get the last verified date - if (rs.getTimestamp("LAST_VERIFIED") != null) { - user.setLastVerified(new Date(rs.getTimestamp("LAST_VERIFIED").getTime())); - } - - // add the user - users.add(user); - } - - // the select statement performs a left join since the desired - // user may not have any authorities - String authority = rs.getString("ROLE"); - if (StringUtils.isNotBlank(authority)) { - user.getAuthorities().add(Authority.valueOfAuthority(authority)); - } - } - - return users; - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } finally { - RepositoryUtils.closeQuietly(rs); - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public Set findUserGroups() throws DataAccessException { - Set userGroups = new HashSet<>(); - - PreparedStatement statement = null; - ResultSet rs = null; - try { - // create the connection and obtain a statement - statement = connection.prepareStatement(SELECT_USER_GROUPS); - - // execute the query - rs = statement.executeQuery(); - - // get each user group - while (rs.next()) { - userGroups.add(rs.getString("USER_GROUP")); - } - - return userGroups; - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } finally { - RepositoryUtils.closeQuietly(rs); - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public Set findUsersForGroup(String group) throws DataAccessException { - Set users = new HashSet<>(); - - PreparedStatement statement = null; - ResultSet rs = null; - try { - // create the connection and obtain a statement - statement = connection.prepareStatement(SELECT_USER_GROUP); - statement.setString(1, NiFiUser.ANONYMOUS_USER_IDENTITY); - statement.setString(2, group); - - // execute the query - rs = statement.executeQuery(); - - // create the user - NiFiUser user = null; - - // go through the user and its roles - while (rs.next()) { - // get the user id for the current record - String userId = rs.getString("ID"); - - // create the user during the first iteration - if (user == null || !userId.equals(user.getId())) { - user = new NiFiUser(); - user.setId(userId); - user.setIdentity(rs.getString("IDENTITY")); - user.setUserName(rs.getString("USER_NAME")); - user.setUserGroup(rs.getString("USER_GROUP")); - user.setJustification(rs.getString("JUSTIFICATION")); - user.setStatus(AccountStatus.valueOfStatus(rs.getString("STATUS"))); - - // set the creation date - user.setCreation(new Date(rs.getTimestamp("CREATION").getTime())); - - // get the last accessed date - if (rs.getTimestamp("LAST_ACCESSED") != null) { - user.setLastAccessed(new Date(rs.getTimestamp("LAST_ACCESSED").getTime())); - } - - // get the last verified date - if (rs.getTimestamp("LAST_VERIFIED") != null) { - user.setLastVerified(new Date(rs.getTimestamp("LAST_VERIFIED").getTime())); - } - - // add the user - users.add(user); - } - - // the select statement performs a left join since the desired - // user may not have any authorities - String authority = rs.getString("ROLE"); - if (StringUtils.isNotBlank(authority)) { - user.getAuthorities().add(Authority.valueOfAuthority(authority)); - } - } - - return users; - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } finally { - RepositoryUtils.closeQuietly(rs); - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public NiFiUser findUserById(String id) throws DataAccessException { - PreparedStatement statement = null; - ResultSet rs = null; - try { - // create the connection and obtain a statement - statement = connection.prepareStatement(SELECT_USER_BY_ID); - statement.setString(1, id); - - // execute the query - rs = statement.executeQuery(); - - // create the user - NiFiUser user = null; - - // go through the user and its roles - while (rs.next()) { - // create the user during the first iteration - if (user == null) { - user = new NiFiUser(); - user.setId(rs.getString("ID")); - user.setIdentity(rs.getString("IDENTITY")); - user.setUserName(rs.getString("USER_NAME")); - user.setUserGroup(rs.getString("USER_GROUP")); - user.setJustification(rs.getString("JUSTIFICATION")); - user.setStatus(AccountStatus.valueOfStatus(rs.getString("STATUS"))); - - // set the creation date - user.setCreation(new Date(rs.getTimestamp("CREATION").getTime())); - - // get the last accessed date - if (rs.getTimestamp("LAST_ACCESSED") != null) { - user.setLastAccessed(new Date(rs.getTimestamp("LAST_ACCESSED").getTime())); - } - - // get the last verified date - if (rs.getTimestamp("LAST_VERIFIED") != null) { - user.setLastVerified(new Date(rs.getTimestamp("LAST_VERIFIED").getTime())); - } - } - - // the select statement performs a left join since the desired - // user may not have any authorities - String authority = rs.getString("ROLE"); - if (StringUtils.isNotBlank(authority)) { - user.getAuthorities().add(Authority.valueOfAuthority(authority)); - } - } - - return user; - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } finally { - RepositoryUtils.closeQuietly(rs); - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public NiFiUser findUserByDn(String dn) throws DataAccessException { - PreparedStatement statement = null; - ResultSet rs = null; - try { - // create the connection and obtain a statement - statement = connection.prepareStatement(SELECT_USER_BY_USER); - statement.setString(1, dn); - - // execute the query - rs = statement.executeQuery(); - - // create the user - NiFiUser user = null; - - // go through the user and its roles - while (rs.next()) { - // create the user during the first iteration - if (user == null) { - user = new NiFiUser(); - user.setId(rs.getString("ID")); - user.setIdentity(rs.getString("IDENTITY")); - user.setUserName(rs.getString("USER_NAME")); - user.setUserGroup(rs.getString("USER_GROUP")); - user.setJustification(rs.getString("JUSTIFICATION")); - user.setStatus(AccountStatus.valueOfStatus(rs.getString("STATUS"))); - - // set the creation date - user.setCreation(new Date(rs.getTimestamp("CREATION").getTime())); - - // get the last accessed date - if (rs.getTimestamp("LAST_ACCESSED") != null) { - user.setLastAccessed(new Date(rs.getTimestamp("LAST_ACCESSED").getTime())); - } - - // get the last verified date - if (rs.getTimestamp("LAST_VERIFIED") != null) { - user.setLastVerified(new Date(rs.getTimestamp("LAST_VERIFIED").getTime())); - } - } - - // the select statement performs a left join since the desired - // user may not have any authorities - String authority = rs.getString("ROLE"); - if (StringUtils.isNotBlank(authority)) { - user.getAuthorities().add(Authority.valueOfAuthority(authority)); - } - } - - return user; - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } finally { - RepositoryUtils.closeQuietly(rs); - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public NiFiUser createUser(NiFiUser user) throws DataAccessException { - if (user.getIdentity() == null) { - throw new IllegalArgumentException("User identity must be specified."); - } - - // ensure the user identity is not too lengthy - if (user.getIdentity().length() > 4096) { - throw new IllegalArgumentException("User identity must be less than 4096 characters."); - } - - PreparedStatement statement = null; - ResultSet rs = null; - try { - final String id = UUID.nameUUIDFromBytes(user.getIdentity().getBytes(StandardCharsets.UTF_8)).toString(); - - // create a statement - statement = connection.prepareStatement(INSERT_USER, Statement.RETURN_GENERATED_KEYS); - statement.setString(1, id); - statement.setString(2, StringUtils.left(user.getIdentity(), 4096)); - statement.setString(3, StringUtils.left(user.getUserName(), 4096)); - statement.setString(4, StringUtils.left(user.getUserGroup(), 100)); - if (user.getLastVerified() != null) { - statement.setTimestamp(5, new java.sql.Timestamp(user.getLastVerified().getTime())); - } else { - statement.setTimestamp(5, null); - } - statement.setString(6, StringUtils.left(user.getJustification(), 500)); - statement.setString(7, user.getStatus().toString()); - - // insert the user - int updateCount = statement.executeUpdate(); - if (updateCount == 1) { - user.setId(id); - } else { - throw new DataAccessException("Unable to insert user."); - } - - return user; - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } catch (DataAccessException dae) { - throw dae; - } finally { - RepositoryUtils.closeQuietly(rs); - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public void deleteUser(String id) throws DataAccessException { - // ensure there are some authorities to create - PreparedStatement statement = null; - try { - // add each authority for the specified user - statement = connection.prepareStatement(DELETE_USER); - statement.setString(1, id); - - // insert the authorities - statement.executeUpdate(); - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } catch (DataAccessException dae) { - throw dae; - } finally { - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public void updateUser(NiFiUser user) throws DataAccessException { - PreparedStatement statement = null; - try { - // create a statement - statement = connection.prepareStatement(UPDATE_USER); - statement.setString(1, StringUtils.left(user.getIdentity(), 4096)); - statement.setString(2, StringUtils.left(user.getUserName(), 4096)); - statement.setString(3, StringUtils.left(user.getUserGroup(), 100)); - statement.setString(6, StringUtils.left(user.getJustification(), 500)); - statement.setString(7, user.getStatus().toString()); - statement.setString(8, user.getId()); - - // set the last accessed time accordingly - if (user.getLastAccessed() == null) { - statement.setNull(4, Types.TIMESTAMP); - } else { - statement.setTimestamp(4, new java.sql.Timestamp(user.getLastAccessed().getTime())); - } - - // set the last verified time accordingly - if (user.getLastVerified() == null) { - statement.setNull(5, Types.TIMESTAMP); - } else { - statement.setTimestamp(5, new java.sql.Timestamp(user.getLastVerified().getTime())); - } - - // perform the update - int updateCount = statement.executeUpdate(); - if (updateCount != 1) { - throw new DataAccessException("Unable to update user."); - } - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } catch (DataAccessException dae) { - throw dae; - } finally { - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public void updateGroupStatus(String group, AccountStatus status) throws DataAccessException { - PreparedStatement statement = null; - try { - // create a statement - statement = connection.prepareStatement(UPDATE_USER_GROUP_STATUS); - statement.setString(1, status.toString()); - statement.setString(2, group); - - // perform the update - statement.executeUpdate(); - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } catch (DataAccessException dae) { - throw dae; - } finally { - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public void updateGroupVerification(String group, Date lastVerified) throws DataAccessException { - PreparedStatement statement = null; - try { - // create a statement - statement = connection.prepareStatement(UPDATE_USER_GROUP_VERIFICATION); - - // set the last verified time accordingly - if (lastVerified == null) { - statement.setNull(1, Types.TIMESTAMP); - } else { - statement.setTimestamp(1, new java.sql.Timestamp(lastVerified.getTime())); - } - - // set the group - statement.setString(2, group); - - // perform the update - statement.executeUpdate(); - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } catch (DataAccessException dae) { - throw dae; - } finally { - RepositoryUtils.closeQuietly(statement); - } - } - - @Override - public void ungroup(String group) throws DataAccessException { - PreparedStatement statement = null; - try { - // create a statement - statement = connection.prepareStatement(UNGROUP_GROUP); - statement.setString(1, group); - - // perform the update - statement.executeUpdate(); - } catch (SQLException sqle) { - throw new DataAccessException(sqle); - } catch (DataAccessException dae) { - throw dae; - } finally { - RepositoryUtils.closeQuietly(statement); - } - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountNotFoundException.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountNotFoundException.java deleted file mode 100644 index 88287ce23b..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountNotFoundException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service; - -/** - * Exception to indicate that the user account is disabled. - */ -public class AccountNotFoundException extends RuntimeException { - - public AccountNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - - public AccountNotFoundException(Throwable cause) { - super(cause); - } - - public AccountNotFoundException(String message, Throwable cause) { - super(message, cause); - } - - public AccountNotFoundException(String message) { - super(message); - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountPendingException.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountPendingException.java deleted file mode 100644 index dacc483148..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountPendingException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service; - -/** - * Exception to indicate that the user has already submitting an account request - * and that request is still pending. - */ -public class AccountPendingException extends RuntimeException { - - public AccountPendingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - - public AccountPendingException(Throwable cause) { - super(cause); - } - - public AccountPendingException(String message, Throwable cause) { - super(message, cause); - } - - public AccountPendingException(String message) { - super(message); - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountDisabledException.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/KeyService.java similarity index 53% rename from nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountDisabledException.java rename to nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/KeyService.java index e8b3d1098e..45434756b9 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/AccountDisabledException.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/KeyService.java @@ -16,25 +16,34 @@ */ package org.apache.nifi.admin.service; +import org.apache.nifi.key.Key; + /** - * Exception to indicate that the user account is disabled. + * Manages NiFi user keys. */ -public class AccountDisabledException extends RuntimeException { +public interface KeyService { - public AccountDisabledException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + /** + * Gets a key for the specified user identity. Returns null if the user has not had a key issued + * + * @param id The key id + * @return The key or null + */ + Key getKey(int id); - public AccountDisabledException(Throwable cause) { - super(cause); - } - - public AccountDisabledException(String message, Throwable cause) { - super(message, cause); - } - - public AccountDisabledException(String message) { - super(message); - } + /** + * Gets a key for the specified user identity. If a key does not exist, one will be created. + * + * @param identity The user identity + * @return The key + * @throws AdministrationException if it failed to get/create the key + */ + Key getOrCreateKey(String identity); + /** + * Deletes keys for the specified identity. + * + * @param identity The user identity + */ + void deleteKey(String identity); } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/UserService.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/UserService.java deleted file mode 100644 index 4ea71af16d..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/UserService.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.DownloadAuthorization; -import org.apache.nifi.key.Key; -import org.apache.nifi.user.NiFiUser; -import org.apache.nifi.user.NiFiUserGroup; - -/** - * Manages NiFi user accounts. - */ -public interface UserService { - - /** - * Creates a new user account using the specified dn and justification. - * - * @param dn user dn - * @param justification why the account is necessary - * @return the created NiFiUser - */ - NiFiUser createPendingUserAccount(String dn, String justification); - - /** - * @return Determines if there are any PENDING user accounts present - */ - Boolean hasPendingUserAccount(); - - /** - * @param dnChain user dn chain - * @param attributes attributes for authorization request - * @return Determines if the users in the dnChain are authorized to download content with the specified attributes - */ - DownloadAuthorization authorizeDownload(List dnChain, Map attributes); - - /** - * Updates a user group using the specified group comprised of the specified users. Returns all the users that are currently in the specified group. - * - * @param group group - * @param userIds users - * @param authorities auths - * @return a user group - */ - NiFiUserGroup updateGroup(String group, Set userIds, Set authorities); - - /** - * Authorizes the user specified. - * - * @param dn user dn - * @return the user for the given dn if found - */ - NiFiUser checkAuthorization(String dn); - - /** - * Deletes the user with the specified id. - * - * @param id user identifier - */ - void deleteUser(String id); - - /** - * Disables the specified users account. - * - * @param id user identifier - * @return user for the given identifier - */ - NiFiUser disable(String id); - - /** - * Disables the specified user group. - * - * @param group to disable - * @return user group - */ - NiFiUserGroup disableGroup(String group); - - /** - * Updates the specified user with the specified authorities. - * - * @param id identifier of user - * @param authorities auths to set - * @return the updated user - */ - NiFiUser update(String id, Set authorities); - - /** - * Invalidates the specified user account. - * - * @param id identifier of user account to invalidate - */ - void invalidateUserAccount(String id); - - /** - * Invalidates the user accounts associated with the specified user group. - * - * @param group to invalidate user accounts on - */ - void invalidateUserGroupAccount(String group); - - /** - * Ungroups the specified group. - * - * @param group to split up - */ - void ungroup(String group); - - /** - * Ungroups the specified user. - * - * @param id user to ungroup - */ - void ungroupUser(String id); - - /** - * Returns a collection of all NiFiUsers. - * - * @return Collection of users - */ - Collection getUsers(); - - /** - * Finds the specified user by id. - * - * @param id of the user - * @return the user object - */ - NiFiUser getUserById(String id); - - /** - * Finds the specified user by dn. - * - * @param dn the user dn - * @return the newly created user - * @throws AdministrationException ae - */ - NiFiUser getUserByDn(String dn); - - /** - * Gets a key for the specified user identity. Returns null if the user has not had a key issued - * - * @param id The key id - * @return The key or null - */ - Key getKey(int id); - - /** - * Gets a key for the specified user identity. If a key does not exist, one will be created. - * - * @param identity The user identity - * @return The key - * @throws AdministrationException if it failed to get/create the key - */ - Key getOrCreateKey(String identity); - - /** - * Deletes keys for the specified identity. - * - * @param identity The user identity - */ - void deleteKey(String identity); -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AbstractUserAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AbstractUserAction.java deleted file mode 100644 index 69c6c1f59a..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AbstractUserAction.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Date; -import java.util.EnumSet; -import java.util.Set; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; - -/** - * - * @param type of user action - */ -public abstract class AbstractUserAction implements AdministrationAction { - - /** - * Determines the authorities that need to be added to the specified user. - * - * @param user user - * @param authorities auths - * @return authorities to add - */ - protected Set determineAuthoritiesToAdd(NiFiUser user, Set authorities) { - // not using copyOf since authorities may be empty and copyOf can throw an IllegalArgumentException when empty - Set authoritiesToAdd = EnumSet.noneOf(Authority.class); - authoritiesToAdd.addAll(authorities); - - // identify the authorities that need to be inserted - authoritiesToAdd.removeAll(user.getAuthorities()); - - // return the desired authorities - return authoritiesToAdd; - } - - /** - * Determines the authorities that need to be removed from the specified - * user. - * - * @param user user - * @param authorities auths - * @return auths to remove - */ - protected Set determineAuthoritiesToRemove(NiFiUser user, Set authorities) { - Set authoritiesToRemove = EnumSet.copyOf(user.getAuthorities()); - - // identify the authorities that need to be removed - authoritiesToRemove.removeAll(authorities); - - // return the desired authorities - return authoritiesToRemove; - } - - /** - * Verifies the specified users account. Includes obtaining the authorities - * and group according to the specified authority provider. - * - * @param authorityProvider provider - * @param user user to verify - */ - protected void verifyAccount(AuthorityProvider authorityProvider, NiFiUser user) { - // load the roles for the user - Set authorities = authorityProvider.getAuthorities(user.getIdentity()); - - // update the user's authorities - user.getAuthorities().clear(); - user.getAuthorities().addAll(authorities); - - // get the user group - user.setUserGroup(authorityProvider.getGroupForUser(user.getIdentity())); - - // update the users status in case they were previously pending or disabled - user.setStatus(AccountStatus.ACTIVE); - - // update the users last verified time - this timestampt shouldn't be record - // until the both the user's authorities and group have been synced - Date now = new Date(); - user.setLastVerified(now); - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AddActionsAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AddActionsAction.java index db1d8a287d..937603e1ef 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AddActionsAction.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AddActionsAction.java @@ -19,7 +19,6 @@ package org.apache.nifi.admin.service.action; import org.apache.nifi.action.Action; import org.apache.nifi.admin.dao.ActionDAO; import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.authorization.AuthorityProvider; import java.util.Collection; @@ -35,7 +34,7 @@ public class AddActionsAction implements AdministrationAction { } @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { + public Void execute(DAOFactory daoFactory) { ActionDAO actionDao = daoFactory.getActionDAO(); // add each action diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AdministrationAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AdministrationAction.java index f1795a9157..141aa84882 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AdministrationAction.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AdministrationAction.java @@ -17,7 +17,6 @@ package org.apache.nifi.admin.service.action; import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.authorization.AuthorityProvider; /** * Defines the administration action. Actions are provided a DAO factory and @@ -31,8 +30,7 @@ public interface AdministrationAction { * Performs an action using the specified DAOFactory and AuthorityProvider. * * @param daoFactory factory - * @param authorityProvider provider * @return action result */ - T execute(DAOFactory daoFactory, AuthorityProvider authorityProvider); + T execute(DAOFactory daoFactory); } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AuthorizeDownloadAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AuthorizeDownloadAction.java deleted file mode 100644 index d1b994c366..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AuthorizeDownloadAction.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.List; -import java.util.Map; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.DownloadAuthorization; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; - -/** - * Attempts to obtain authorization to download the content with the specified - * attributes for the specified user. - */ -public class AuthorizeDownloadAction implements AdministrationAction { - - private final List dnChain; - private final Map attributes; - - public AuthorizeDownloadAction(List dnChain, Map attributes) { - this.dnChain = dnChain; - this.attributes = attributes; - } - - @Override - public DownloadAuthorization execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { - try { - return authorityProvider.authorizeDownload(dnChain, attributes); - } catch (UnknownIdentityException uie) { - throw new AccountNotFoundException(uie.getMessage(), uie); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(aae.getMessage(), aae); - } - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AuthorizeUserAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AuthorizeUserAction.java deleted file mode 100644 index ed4dfa1886..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/AuthorizeUserAction.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Calendar; -import java.util.Date; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountDisabledException; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AccountPendingException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.security.util.CertificateUtils; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; - -/** - * - */ -public class AuthorizeUserAction extends AbstractUserAction { - - private final String identity; - private final int cacheDurationSeconds; - - public AuthorizeUserAction(String identity, int cacheDurationSeconds) { - this.identity = identity; - this.cacheDurationSeconds = cacheDurationSeconds; - } - - @Override - public NiFiUser execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - UserDAO userDao = daoFactory.getUserDAO(); - - // get the user - NiFiUser user = userDao.findUserByDn(identity); - - // verify the user was found - if (user == null) { - // determine whether this users exists - boolean doesDnExist = false; - try { - doesDnExist = authorityProvider.doesDnExist(identity); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access authority details: %s", aae.getMessage()), aae); - } - - // if the authority provider has the details for this user, create the account - if (doesDnExist) { - // create the user - user = new NiFiUser(); - user.setIdentity(identity); - user.setUserName(CertificateUtils.extractUsername(identity)); - user.setJustification("User details specified by authority provider."); - - try { - // verify the users account - verifyAccount(authorityProvider, user); - - // get the date used for verification - Date now = user.getLastVerified(); - - // update the last accessed field - user.setLastAccessed(now); - user.setCreation(now); - - // create the new user account - CreateUserAction createUser = new CreateUserAction(user); - createUser.execute(daoFactory, authorityProvider); - } catch (UnknownIdentityException uie) { - // strange since the provider just reported this dn existed but handleing anyways... - throw new AccountNotFoundException(String.format("Unable to verify access for %s.", identity)); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access authority details: %s", aae.getMessage()), aae); - } - } else { - throw new AccountNotFoundException(String.format("Unable to verify access for %s.", identity)); - } - } else { - Throwable providerError = null; - - // verify the users account if necessary - if (isAccountVerificationRequired(user)) { - try { - // verify the users account - verifyAccount(authorityProvider, user); - - // update the last accessed field - user.setLastAccessed(user.getLastVerified()); - } catch (UnknownIdentityException uie) { - // check the account status before attempting to update the account - depending on the account - // status we might not need to update the account - checkAccountStatus(user); - - // the user is currently active and they were not found in the providers - disable the account... - user.setStatus(AccountStatus.DISABLED); - - // record the exception - providerError = uie; - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access authority details: %s", aae.getMessage()), aae); - } - } else { - // verfiy the users account status before allowing access. - checkAccountStatus(user); - - // update the users last accessed time - user.setLastAccessed(new Date()); - } - - // persist the user's updates - UpdateUserCacheAction updateUser = new UpdateUserCacheAction(user); - updateUser.execute(daoFactory, authorityProvider); - - // persist the user's authorities - UpdateUserAuthoritiesCacheAction updateUserAuthorities = new UpdateUserAuthoritiesCacheAction(user); - updateUserAuthorities.execute(daoFactory, authorityProvider); - - if (providerError != null) { - throw new AccountDisabledException(String.format("User credentials for %s were not found. This account has been disabled.", user.getIdentity()), providerError); - } - } - - return user; - } - - /** - * @return Determines if account verification is required - */ - private boolean isAccountVerificationRequired(NiFiUser user) { - // accounts that have never been verified obviously needs to be re-verified - if (user.getLastVerified() == null) { - return true; - } - - // create a calendar and substract the threshold - anything - // before this time will need to be re-verified - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.SECOND, -cacheDurationSeconds); - - return user.getLastVerified().before(calendar.getTime()); - } - - /** - * Checks the account status of the specified user. - * - * @param user to check - */ - private void checkAccountStatus(NiFiUser user) { - if (AccountStatus.DISABLED.equals(user.getStatus())) { - throw new AccountDisabledException(String.format("The account for %s has been disabled.", user.getIdentity())); - } else if (AccountStatus.PENDING.equals(user.getStatus())) { - throw new AccountPendingException(String.format("The account for %s is currently pending approval.", user.getIdentity())); - } - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/CreateUserAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/CreateUserAction.java deleted file mode 100644 index 3833abb6fa..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/CreateUserAction.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Set; -import org.apache.nifi.admin.dao.AuthorityDAO; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.NiFiUser; - -/** - * Action for creating a NiFiUser account. - */ -public class CreateUserAction extends AbstractUserAction { - - private final NiFiUser user; - - public CreateUserAction(NiFiUser user) { - this.user = user; - } - - @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - UserDAO userDao = daoFactory.getUserDAO(); - AuthorityDAO authorityDao = daoFactory.getAuthorityDAO(); - - // create the user entry - userDao.createUser(user); - - // create the authorities - Set authorities = user.getAuthorities(); - authorityDao.createAuthorities(authorities, user.getId()); - - return null; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DeleteKeysAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DeleteKeysAction.java index cd13fa55ee..6b8a2d5264 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DeleteKeysAction.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DeleteKeysAction.java @@ -19,7 +19,6 @@ package org.apache.nifi.admin.service.action; import org.apache.nifi.admin.dao.DAOFactory; import org.apache.nifi.admin.dao.DataAccessException; import org.apache.nifi.admin.dao.KeyDAO; -import org.apache.nifi.authorization.AuthorityProvider; /** * @@ -38,7 +37,7 @@ public class DeleteKeysAction implements AdministrationAction { } @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { + public Void execute(DAOFactory daoFactory) throws DataAccessException { final KeyDAO keyDao = daoFactory.getKeyDAO(); keyDao.deleteKeys(identity); return null; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DeleteUserAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DeleteUserAction.java deleted file mode 100644 index c2695d0f18..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DeleteUserAction.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.AuthorityDAO; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.KeyDAO; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; - -/** - * - */ -public class DeleteUserAction implements AdministrationAction { - - private final String userId; - - /** - * Creates a new transactions for deleting the specified user. - * - * @param userId user identifier - */ - public DeleteUserAction(String userId) { - this.userId = userId; - } - - @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - final AuthorityDAO authorityDAO = daoFactory.getAuthorityDAO(); - final UserDAO userDAO = daoFactory.getUserDAO(); - - // find the user and ensure they are currently revoked - final NiFiUser user = userDAO.findUserById(userId); - - // ensure the user was found - if (user == null) { - throw new AccountNotFoundException(String.format("Unable to find account with ID %s.", userId)); - } - - // ensure the user is in the appropriate state - if (AccountStatus.ACTIVE.equals(user.getStatus())) { - throw new IllegalStateException(String.format("An active user cannot be removed. Revoke user access before attempting to remove.")); - } - - // remove the user's keys - final KeyDAO keyDao = daoFactory.getKeyDAO(); - keyDao.deleteKeys(user.getIdentity()); - - // remove the user and their authorities - authorityDAO.deleteAuthorities(userId); - userDAO.deleteUser(userId); - - return null; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DisableUserAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DisableUserAction.java deleted file mode 100644 index bf7eae3414..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DisableUserAction.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.KeyDAO; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class DisableUserAction implements AdministrationAction { - - private static final Logger logger = LoggerFactory.getLogger(DisableUserAction.class); - - private final String id; - - public DisableUserAction(String id) { - this.id = id; - } - - @Override - public NiFiUser execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - UserDAO userDao = daoFactory.getUserDAO(); - - // get the user - NiFiUser user = userDao.findUserById(id); - - // ensure the user exists - if (user == null) { - throw new AccountNotFoundException(String.format("Unable to find account with ID %s.", id)); - } - - // update the account - user.setStatus(AccountStatus.DISABLED); - user.setUserGroup(null); - - // update the user locally - userDao.updateUser(user); - - // remove the user's keys - KeyDAO keyDao = daoFactory.getKeyDAO(); - keyDao.deleteKeys(user.getIdentity()); - - try { - // revoke the user in the authority provider - authorityProvider.revokeUser(user.getIdentity()); - } catch (UnknownIdentityException uie) { - // user identity is not known - logger.info(String.format("User %s has already been removed from the authority provider.", user.getIdentity())); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to revoke user '%s': %s", user.getIdentity(), aae.getMessage()), aae); - } - - return user; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DisableUserGroupAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DisableUserGroupAction.java deleted file mode 100644 index c6480ed63e..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/DisableUserGroupAction.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Set; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.KeyDAO; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; -import org.apache.nifi.user.NiFiUserGroup; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class DisableUserGroupAction implements AdministrationAction { - - private static final Logger logger = LoggerFactory.getLogger(DisableUserGroupAction.class); - - private final String group; - - public DisableUserGroupAction(final String group) { - this.group = group; - } - - @Override - public NiFiUserGroup execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - final UserDAO userDao = daoFactory.getUserDAO(); - final Set users = userDao.findUsersForGroup(group); - - // delete the keys for each user - final KeyDAO keyDao = daoFactory.getKeyDAO(); - for (final NiFiUser user : users) { - keyDao.deleteKeys(user.getIdentity()); - } - - // update the user group locally - userDao.updateGroupStatus(group, AccountStatus.DISABLED); - - // populate the group details - final NiFiUserGroup userGroup = new NiFiUserGroup(); - userGroup.setGroup(group); - userGroup.setUsers(userDao.findUsersForGroup(group)); - - try { - // revoke the user in the authority provider - authorityProvider.revokeGroup(group); - } catch (UnknownIdentityException uie) { - // user identity is not known - logger.info(String.format("User group %s has already been removed from the authority provider.", group)); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to revoke user group '%s': %s", group, aae.getMessage()), aae); - } - - return userGroup; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/FindUserByDnAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/FindUserByDnAction.java deleted file mode 100644 index 8e5b574d50..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/FindUserByDnAction.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.NiFiUser; - -/** - * - */ -public class FindUserByDnAction implements AdministrationAction { - - private final String dn; - - /** - * Creates a new transactions for getting a user with the specified DN. - * - * @param dn The DN of the user to obtain - */ - public FindUserByDnAction(String dn) { - this.dn = dn; - } - - @Override - public NiFiUser execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - // get a UserDAO - UserDAO userDAO = daoFactory.getUserDAO(); - - // return the desired user - return userDAO.findUserByDn(dn); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/FindUserByIdAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/FindUserByIdAction.java deleted file mode 100644 index 0a10841368..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/FindUserByIdAction.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.NiFiUser; - -public class FindUserByIdAction implements AdministrationAction { - - private final String id; - - /** - * Creates a new transactions for getting a user with the specified id. - * - * @param id of user - */ - public FindUserByIdAction(String id) { - this.id = id; - } - - @Override - public NiFiUser execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - // get a UserDAO - UserDAO userDAO = daoFactory.getUserDAO(); - - // return the desired user - return userDAO.findUserById(id); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetActionAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetActionAction.java index 1dc558840f..28bfe2279d 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetActionAction.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetActionAction.java @@ -19,7 +19,6 @@ package org.apache.nifi.admin.service.action; import org.apache.nifi.action.Action; import org.apache.nifi.admin.dao.ActionDAO; import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.authorization.AuthorityProvider; /** * Gets the action with the specified id. @@ -33,7 +32,7 @@ public class GetActionAction implements AdministrationAction { } @Override - public Action execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { + public Action execute(DAOFactory daoFactory) { ActionDAO actionDao = daoFactory.getActionDAO(); return actionDao.getAction(id); } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetActionsAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetActionsAction.java index 3b82d7985f..f975393b1f 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetActionsAction.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetActionsAction.java @@ -16,13 +16,13 @@ */ package org.apache.nifi.admin.service.action; -import java.util.Date; import org.apache.nifi.admin.dao.ActionDAO; import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.authorization.AuthorityProvider; import org.apache.nifi.history.History; import org.apache.nifi.history.HistoryQuery; +import java.util.Date; + /** * Get all actions that match the specified query. */ @@ -35,7 +35,7 @@ public class GetActionsAction implements AdministrationAction { } @Override - public History execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { + public History execute(DAOFactory daoFactory) { ActionDAO actionDao = daoFactory.getActionDAO(); // find all matching history diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetKeyByIdAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetKeyByIdAction.java index 8763b9d0e3..7ef2272083 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetKeyByIdAction.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetKeyByIdAction.java @@ -17,8 +17,6 @@ package org.apache.nifi.admin.service.action; import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.authorization.AuthorityProvider; - import org.apache.nifi.admin.dao.KeyDAO; import org.apache.nifi.key.Key; @@ -34,7 +32,7 @@ public class GetKeyByIdAction implements AdministrationAction { } @Override - public Key execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { + public Key execute(DAOFactory daoFactory) { final KeyDAO keyDao = daoFactory.getKeyDAO(); return keyDao.findKeyById(id); } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetKeyByIdentityAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetKeyByIdentityAction.java index 9bcb0b3f0e..3dd37940a5 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetKeyByIdentityAction.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetKeyByIdentityAction.java @@ -17,8 +17,6 @@ package org.apache.nifi.admin.service.action; import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.authorization.AuthorityProvider; - import org.apache.nifi.admin.dao.KeyDAO; import org.apache.nifi.key.Key; @@ -34,7 +32,7 @@ public class GetKeyByIdentityAction implements AdministrationAction { } @Override - public Key execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { + public Key execute(DAOFactory daoFactory) { final KeyDAO keyDao = daoFactory.getKeyDAO(); return keyDao.findLatestKeyByIdentity(identity); } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetOrCreateKeyAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetOrCreateKeyAction.java index bb85b6fe26..8c862265c9 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetOrCreateKeyAction.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetOrCreateKeyAction.java @@ -17,8 +17,6 @@ package org.apache.nifi.admin.service.action; import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.authorization.AuthorityProvider; - import org.apache.nifi.admin.dao.KeyDAO; import org.apache.nifi.key.Key; @@ -34,7 +32,7 @@ public class GetOrCreateKeyAction implements AdministrationAction { } @Override - public Key execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { + public Key execute(DAOFactory daoFactory) { final KeyDAO keyDao = daoFactory.getKeyDAO(); Key key = keyDao.findLatestKeyByIdentity(identity); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetPreviousValues.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetPreviousValues.java index 569439baa9..337643f226 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetPreviousValues.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetPreviousValues.java @@ -16,13 +16,13 @@ */ package org.apache.nifi.admin.service.action; -import java.util.List; -import java.util.Map; import org.apache.nifi.admin.dao.ActionDAO; import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.authorization.AuthorityProvider; import org.apache.nifi.history.PreviousValue; +import java.util.List; +import java.util.Map; + /** * Gets the action with the specified id. */ @@ -35,7 +35,7 @@ public class GetPreviousValues implements AdministrationAction> execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { + public Map> execute(DAOFactory daoFactory) { ActionDAO actionDao = daoFactory.getActionDAO(); return actionDao.getPreviousValues(componentId); } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetUserGroupAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetUserGroupAction.java deleted file mode 100644 index 5377c4650b..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetUserGroupAction.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.NiFiUserGroup; - -/** - * - */ -public class GetUserGroupAction implements AdministrationAction { - - private final String group; - - public GetUserGroupAction(String group) { - this.group = group; - } - - @Override - public NiFiUserGroup execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - final UserDAO userDAO = daoFactory.getUserDAO(); - final NiFiUserGroup userGroup = new NiFiUserGroup(); - - // set the group - userGroup.setGroup(group); - - // get the users in this group - userGroup.setUsers(userDAO.findUsersForGroup(group)); - - // return the group - return userGroup; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetUsersAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetUsersAction.java deleted file mode 100644 index 42d180e5ac..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/GetUsersAction.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Collection; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.NiFiUser; - -/** - * - */ -public class GetUsersAction implements AdministrationAction> { - - @Override - public Collection execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - // get a UserDAO - UserDAO userDAO = daoFactory.getUserDAO(); - - // return the desired user - return userDAO.findUsers(); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/HasPendingUserAccounts.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/HasPendingUserAccounts.java deleted file mode 100644 index 3325642fb1..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/HasPendingUserAccounts.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.AuthorityProvider; - -/** - * Action for creating a NiFiUser account. - */ -public class HasPendingUserAccounts extends AbstractUserAction { - - @Override - public Boolean execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - UserDAO userDao = daoFactory.getUserDAO(); - return userDao.hasPendingUserAccounts(); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/InvalidateUserAccountAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/InvalidateUserAccountAction.java deleted file mode 100644 index 14596b2bf1..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/InvalidateUserAccountAction.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.NiFiUser; - -/** - * Invalidates a user account. - */ -public class InvalidateUserAccountAction implements AdministrationAction { - - private final String id; - - public InvalidateUserAccountAction(String id) { - this.id = id; - } - - @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - UserDAO userDao = daoFactory.getUserDAO(); - - // get the current user details - NiFiUser user = userDao.findUserById(id); - - // ensure the user exists - if (user == null) { - throw new AccountNotFoundException(String.format("Unable to find account with ID %s.", id)); - } - - // invalidate the user account - user.setLastVerified(null); - - // create the user entry - userDao.updateUser(user); - - return null; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/InvalidateUserGroupAccountsAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/InvalidateUserGroupAccountsAction.java deleted file mode 100644 index 0cb7e144b2..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/InvalidateUserGroupAccountsAction.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.AuthorityProvider; - -/** - * Invalidates a user account. - */ -public class InvalidateUserGroupAccountsAction implements AdministrationAction { - - private final String group; - - public InvalidateUserGroupAccountsAction(String group) { - this.group = group; - } - - @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - UserDAO userDao = daoFactory.getUserDAO(); - - // create the user entry - userDao.updateGroupVerification(group, null); - - return null; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/PurgeActionsAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/PurgeActionsAction.java index 6928e0dfe7..9d970dc766 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/PurgeActionsAction.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/PurgeActionsAction.java @@ -19,7 +19,6 @@ package org.apache.nifi.admin.service.action; import org.apache.nifi.action.Action; import org.apache.nifi.admin.dao.ActionDAO; import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.authorization.AuthorityProvider; import java.util.Date; @@ -37,7 +36,7 @@ public class PurgeActionsAction implements AdministrationAction { } @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { + public Void execute(DAOFactory daoFactory) { ActionDAO actionDao = daoFactory.getActionDAO(); // remove the corresponding actions diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/RequestUserAccountAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/RequestUserAccountAction.java deleted file mode 100644 index 198a32dc7c..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/RequestUserAccountAction.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Date; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.security.util.CertificateUtils; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; - -/** - * - */ -public class RequestUserAccountAction implements AdministrationAction { - - private final String identity; - private final String justification; - - public RequestUserAccountAction(String identity, String justification) { - this.identity = identity; - this.justification = justification; - } - - @Override - public NiFiUser execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - UserDAO userDao = daoFactory.getUserDAO(); - - // determine if this user already exists - NiFiUser user = userDao.findUserByDn(identity); - if (user != null) { - throw new IllegalArgumentException(String.format("User account for %s already exists.", identity)); - } - - // create the user - user = new NiFiUser(); - user.setIdentity(identity); - user.setUserName(CertificateUtils.extractUsername(identity)); - user.setJustification(justification); - user.setStatus(AccountStatus.PENDING); - - // update user timestamps - Date now = new Date(); - user.setCreation(now); - - // create the new user account - userDao.createUser(user); - - return user; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/SeedUserAccountsAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/SeedUserAccountsAction.java deleted file mode 100644 index c16cc712f2..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/SeedUserAccountsAction.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.HashSet; -import java.util.Set; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.security.util.CertificateUtils; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Seeds the user accounts. This action is performed at start up because it - * takes the users specified in the authority provider and makes them available - * to be seen in the UI. This happens because the UI loads the users from the - * cache. Without pre loading the users, the table in the UI would only show a - * given user once they have visited the application. - */ -public class SeedUserAccountsAction extends AbstractUserAction { - - private static final Logger logger = LoggerFactory.getLogger(SeedUserAccountsAction.class); - - @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - UserDAO userDao = daoFactory.getUserDAO(); - Set authorizedIdentities = new HashSet<>(); - - // get the current user cache - final Set existingUsers; - try { - existingUsers = userDao.findUsers(); - } catch (Exception e) { - // unable to access local cache... start up failure - logger.error(String.format("Unable to get existing user base. Cannot proceed until these users can be " - + "verified against the current authority provider: %s", e)); - throw new AdministrationException(e); - } - - try { - // all users for all roles - for (final Authority authority : Authority.values()) { - authorizedIdentities.addAll(authorityProvider.getUsers(authority)); - } - } catch (AuthorityAccessException aae) { - // unable to access the authority provider... honor the cache - logger.warn("Unable to access authority provider due to " + aae); - return null; - } - - final Set accountsToRevoke = new HashSet<>(existingUsers); - - // persist the users - for (String identity : authorizedIdentities) { - NiFiUser user = null; - try { - // locate the user for this dn - user = userDao.findUserByDn(identity); - boolean newAccount = false; - - // if the user does not exist, create a new account - if (user == null) { - logger.info(String.format("Creating user account: %s", identity)); - newAccount = true; - - // create the user - user = new NiFiUser(); - user.setIdentity(identity); - user.setUserName(CertificateUtils.extractUsername(identity)); - user.setJustification("User details specified by authority provider."); - } else { - logger.info(String.format("User account already created: %s. Updating authorities...", identity)); - } - - // verify the account - verifyAccount(authorityProvider, user); - - // persist the account accordingly - if (newAccount) { - CreateUserAction createUser = new CreateUserAction(user); - createUser.execute(daoFactory, authorityProvider); - } else { - // this is not a new user and we have just verified their - // account, do not revoke... - accountsToRevoke.remove(user); - - // persist the user - UpdateUserCacheAction updateUser = new UpdateUserCacheAction(user); - updateUser.execute(daoFactory, authorityProvider); - - // persist the user's authorities - UpdateUserAuthoritiesCacheAction updateUserAuthorities = new UpdateUserAuthoritiesCacheAction(user); - updateUserAuthorities.execute(daoFactory, authorityProvider); - } - } catch (DataAccessException dae) { - if (user != null) { - logger.warn(String.format("Unable to access account details in local cache for user %s: %s", user, dae.getMessage())); - } else { - logger.warn(String.format("Unable to access account details in local cache: %s", dae.getMessage())); - } - } catch (UnknownIdentityException uie) { - if (user != null) { - logger.warn(String.format("Unable to find account details in authority provider for user %s: %s", user, uie.getMessage())); - } else { - logger.warn(String.format("Unable to find account details in authority provider: %s", uie.getMessage())); - } - } catch (AuthorityAccessException aae) { - logger.warn("Unable to access authority provider due to " + aae); - - // unable to access authority provider for this user, honor the cache for now - accountsToRevoke.remove(user); - } - } - - // remove all users that are no longer in the provider - for (final NiFiUser user : accountsToRevoke) { - // allow pending requests to remain... - if (AccountStatus.PENDING.equals(user.getStatus())) { - continue; - } - - try { - logger.info(String.format("User not authorized with configured provider: %s. Disabling account...", user.getIdentity())); - - // disable the account and reset its last verified timestamp since it was not found - // in the current configured authority provider - user.setStatus(AccountStatus.DISABLED); - user.setLastVerified(null); - - // update the user record - UpdateUserCacheAction updateUser = new UpdateUserCacheAction(user); - updateUser.execute(daoFactory, authorityProvider); - } catch (final Exception e) { - // unable to revoke access for someone we know is not authorized... fail start up - logger.error(String.format("Unable to revoke access for user %s that is no longer authorized: %s", user, e)); - throw new AdministrationException(e); - } - } - - return null; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UngroupUserAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UngroupUserAction.java deleted file mode 100644 index 2604a47ca6..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UngroupUserAction.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.user.NiFiUser; - -/** - * - */ -public class UngroupUserAction extends AbstractUserAction { - - private final String userId; - - public UngroupUserAction(String userId) { - this.userId = userId; - } - - @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { - final UserDAO userDao = daoFactory.getUserDAO(); - - // get the user in question - final NiFiUser user = userDao.findUserById(userId); - - // ensure the user exists - if (user == null) { - throw new AccountNotFoundException(String.format("Unable to find account with ID %s.", userId)); - } - - // set the user group - user.setUserGroup(null); - - // update the user locally - userDao.updateUser(user); - - try { - // update the authority provider - authorityProvider.ungroupUser(user.getIdentity()); - } catch (UnknownIdentityException uie) { - throw new AccountNotFoundException(String.format("Unable to ungroup user '%s': %s", user.getIdentity(), uie.getMessage()), uie); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to ungroup user '%s': %s", user.getIdentity(), aae.getMessage()), aae); - } - - return null; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UngroupUserGroupAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UngroupUserGroupAction.java deleted file mode 100644 index fa24fbeb64..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UngroupUserGroupAction.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; - -/** - * - */ -public class UngroupUserGroupAction extends AbstractUserAction { - - private final String group; - - public UngroupUserGroupAction(String group) { - this.group = group; - } - - @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) { - final UserDAO userDao = daoFactory.getUserDAO(); - - // update the user locally - userDao.ungroup(group); - - try { - // update the authority provider - authorityProvider.ungroup(group); - } catch (UnknownIdentityException uie) { - throw new AccountNotFoundException(String.format("Unable to ungroup '%s': %s", group, uie.getMessage()), uie); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to ungroup '%s': %s", group, aae.getMessage()), aae); - } - - return null; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserAction.java deleted file mode 100644 index ecb91e602c..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserAction.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Date; -import java.util.Set; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.IdentityAlreadyExistsException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Sets user authorities. - */ -public class UpdateUserAction extends AbstractUserAction { - - private static final Logger logger = LoggerFactory.getLogger(UpdateUserAction.class); - - private final String id; - private final Set authorities; - - public UpdateUserAction(String id, Set authorities) { - this.id = id; - this.authorities = authorities; - } - - @Override - public NiFiUser execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException, AdministrationException { - UserDAO userDao = daoFactory.getUserDAO(); - - // get the user - NiFiUser user = userDao.findUserById(id); - - // ensure the user exists - if (user == null) { - throw new AccountNotFoundException(String.format("Unable to find account with ID %s.", id)); - } - - // determine whether this users exists - boolean doesIdentityExist = false; - try { - doesIdentityExist = authorityProvider.doesDnExist(user.getIdentity()); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access authority details: %s", aae.getMessage()), aae); - } - - // if the user already doesn't exist, add them - if (!doesIdentityExist) { - try { - // add the account account and group if necessary - authorityProvider.addUser(user.getIdentity(), user.getUserGroup()); - } catch (final IdentityAlreadyExistsException iaee) { - logger.warn(String.format("User '%s' already exists in the authority provider. Continuing with user update.", user.getIdentity())); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access authorities for '%s': %s", user.getIdentity(), aae.getMessage()), aae); - } - } - - try { - // update the authority provider as approprivate - authorityProvider.setAuthorities(user.getIdentity(), authorities); - } catch (UnknownIdentityException uie) { - throw new AccountNotFoundException(String.format("Unable to modify authorities for '%s': %s.", user.getIdentity(), uie.getMessage()), uie); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access authorities for '%s': %s.", user.getIdentity(), aae.getMessage()), aae); - } - - try { - // get the user group - user.setUserGroup(authorityProvider.getGroupForUser(user.getIdentity())); - } catch (UnknownIdentityException uie) { - throw new AccountNotFoundException(String.format("Unable to determine the group for '%s': %s.", user.getIdentity(), uie.getMessage()), uie); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access the group for '%s': %s.", user.getIdentity(), aae.getMessage()), aae); - } - - // since all the authorities were updated accordingly, set the authorities - user.getAuthorities().clear(); - user.getAuthorities().addAll(authorities); - - // update the users status in case they were previously pending or disabled - user.setStatus(AccountStatus.ACTIVE); - - // update the users last verified time - this timestamp shouldn't be recorded - // until the both the user's authorities and group have been synced - Date now = new Date(); - user.setLastVerified(now); - - // persist the user's updates - UpdateUserCacheAction updateUser = new UpdateUserCacheAction(user); - updateUser.execute(daoFactory, authorityProvider); - - // persist the user's authorities - UpdateUserAuthoritiesCacheAction updateUserAuthorities = new UpdateUserAuthoritiesCacheAction(user); - updateUserAuthorities.execute(daoFactory, authorityProvider); - - // return the user - return user; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserAuthoritiesCacheAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserAuthoritiesCacheAction.java deleted file mode 100644 index 89661b20a6..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserAuthoritiesCacheAction.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Set; -import org.apache.nifi.admin.dao.AuthorityDAO; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.NiFiUser; -import org.apache.commons.collections4.CollectionUtils; - -/** - * Updates a NiFiUser's authorities. Prior to invoking this action, the user's - * authorities should be set according to the business logic of the service in - * question. This should not be invoked directly when attempting to set user - * authorities as the authorityProvider is not called from this action. - */ -public class UpdateUserAuthoritiesCacheAction extends AbstractUserAction { - - private final NiFiUser user; - - public UpdateUserAuthoritiesCacheAction(NiFiUser user) { - this.user = user; - } - - @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - UserDAO userDao = daoFactory.getUserDAO(); - AuthorityDAO authorityDao = daoFactory.getAuthorityDAO(); - - // get the user - NiFiUser currentUser = userDao.findUserById(user.getId()); - - // ensure the user exists - if (currentUser == null) { - throw new AccountNotFoundException(String.format("Unable to find account with ID %s.", user.getId())); - } - - // determine what authorities need to be added/removed - Set authorities = user.getAuthorities(); - Set authoritiesToAdd = determineAuthoritiesToAdd(currentUser, authorities); - Set authoritiesToRemove = determineAuthoritiesToRemove(currentUser, authorities); - - // update the user authorities locally - if (CollectionUtils.isNotEmpty(authoritiesToAdd)) { - authorityDao.createAuthorities(authoritiesToAdd, user.getId()); - } - if (CollectionUtils.isNotEmpty(authoritiesToRemove)) { - authorityDao.deleteAuthorities(authoritiesToRemove, user.getId()); - } - - return null; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserCacheAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserCacheAction.java deleted file mode 100644 index 288e2975d4..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserCacheAction.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.NiFiUser; - -/** - * Updates a NiFiUser. This will not update the user authorities, they must be - * updated with the UpdateUserAuthoritiesAction. - */ -public class UpdateUserCacheAction extends AbstractUserAction { - - private final NiFiUser user; - - public UpdateUserCacheAction(NiFiUser user) { - this.user = user; - } - - @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - UserDAO userDao = daoFactory.getUserDAO(); - - // update the user - userDao.updateUser(user); - - return null; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserGroupAction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserGroupAction.java deleted file mode 100644 index 1d7941f9ba..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/action/UpdateUserGroupAction.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Date; -import java.util.HashSet; -import java.util.Set; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Updates all NiFiUser authorities in a specified group. - */ -public class UpdateUserGroupAction extends AbstractUserAction { - - private static final Logger logger = LoggerFactory.getLogger(UpdateUserGroupAction.class); - - private final String group; - private final Set userIds; - private final Set authorities; - - public UpdateUserGroupAction(String group, Set userIds, Set authorities) { - this.group = group; - this.userIds = userIds; - this.authorities = authorities; - } - - @Override - public Void execute(DAOFactory daoFactory, AuthorityProvider authorityProvider) throws DataAccessException { - if (userIds == null && authorities == null) { - throw new IllegalArgumentException("Must specify user Ids or authorities."); - } - - UserDAO userDao = daoFactory.getUserDAO(); - - // record the new users being added to this group - final Set newUsers = new HashSet<>(); - final Set newUserIdentities = new HashSet<>(); - - // if the user ids have been specified we need to create/update a group using the specified group name - if (userIds != null) { - if (userIds.isEmpty()) { - throw new IllegalArgumentException("When creating a group, at least one user id must be specified."); - } - - // going to create a group using the specified user ids - for (final String userId : userIds) { - // get the user in question - final NiFiUser user = userDao.findUserById(userId); - - // ensure the user exists - if (user == null) { - throw new AccountNotFoundException(String.format("Unable to find account with ID %s.", userId)); - } - - try { - // if the user is unknown to the authority provider we cannot continue - if (!authorityProvider.doesDnExist(user.getIdentity()) || AccountStatus.DISABLED.equals(user.getStatus())) { - throw new IllegalStateException(String.format("Unable to group these users because access for '%s' is not %s.", user.getIdentity(), AccountStatus.ACTIVE.toString())); - } - - // record the user being added to this group - newUsers.add(user); - newUserIdentities.add(user.getIdentity()); - } catch (final AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access authority details: %s", aae.getMessage()), aae); - } - } - - try { - // update the authority provider - authorityProvider.setUsersGroup(newUserIdentities, group); - } catch (UnknownIdentityException uie) { - throw new AccountNotFoundException(String.format("Unable to set user group '%s': %s", StringUtils.join(newUserIdentities, ", "), uie.getMessage()), uie); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to set user group '%s': %s", StringUtils.join(newUserIdentities, ", "), aae.getMessage()), aae); - } - } - - // get all the users that need to be updated - final Set users = new HashSet<>(userDao.findUsersForGroup(group)); - users.addAll(newUsers); - - // ensure the user exists - if (users.isEmpty()) { - throw new AccountNotFoundException(String.format("Unable to find user accounts with group id %s.", group)); - } - - // update each user in this group - for (final NiFiUser user : users) { - // if there are new authorities set them, otherwise refresh them according to the provider - if (authorities != null) { - try { - // update the authority provider as approprivate - authorityProvider.setAuthorities(user.getIdentity(), authorities); - - // since all the authorities were updated accordingly, set the authorities - user.getAuthorities().clear(); - user.getAuthorities().addAll(authorities); - } catch (UnknownIdentityException uie) { - throw new AccountNotFoundException(String.format("Unable to modify authorities for '%s': %s.", user.getIdentity(), uie.getMessage()), uie); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access authorities for '%s': %s.", user.getIdentity(), aae.getMessage()), aae); - } - } else { - try { - // refresh the authorities according to the provider - user.getAuthorities().clear(); - user.getAuthorities().addAll(authorityProvider.getAuthorities(user.getIdentity())); - } catch (UnknownIdentityException uie) { - throw new AccountNotFoundException(String.format("Unable to determine the authorities for '%s': %s.", user.getIdentity(), uie.getMessage()), uie); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access authorities for '%s': %s.", user.getIdentity(), aae.getMessage()), aae); - } - } - - try { - // get the user group - user.setUserGroup(authorityProvider.getGroupForUser(user.getIdentity())); - } catch (UnknownIdentityException uie) { - throw new AccountNotFoundException(String.format("Unable to determine the group for '%s': %s.", user.getIdentity(), uie.getMessage()), uie); - } catch (AuthorityAccessException aae) { - throw new AdministrationException(String.format("Unable to access the group for '%s': %s.", user.getIdentity(), aae.getMessage()), aae); - } - - // update the users status in case they were previously pending or disabled - user.setStatus(AccountStatus.ACTIVE); - - // update the users last verified time - this timestamp shouldn't be recorded - // until the both the user's authorities and group have been synced - Date now = new Date(); - user.setLastVerified(now); - - // persist the user's updates - UpdateUserCacheAction updateUser = new UpdateUserCacheAction(user); - updateUser.execute(daoFactory, authorityProvider); - - // persist the user's authorities - UpdateUserAuthoritiesCacheAction updateUserAuthorities = new UpdateUserAuthoritiesCacheAction(user); - updateUserAuthorities.execute(daoFactory, authorityProvider); - } - - return null; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/impl/StandardKeyService.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/impl/StandardKeyService.java new file mode 100644 index 0000000000..7a7f62da0b --- /dev/null +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/impl/StandardKeyService.java @@ -0,0 +1,161 @@ +/* + * 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. + */ +package org.apache.nifi.admin.service.impl; + +import org.apache.nifi.admin.dao.DataAccessException; +import org.apache.nifi.admin.service.AdministrationException; +import org.apache.nifi.admin.service.KeyService; +import org.apache.nifi.admin.service.action.DeleteKeysAction; +import org.apache.nifi.admin.service.action.GetKeyByIdAction; +import org.apache.nifi.admin.service.action.GetOrCreateKeyAction; +import org.apache.nifi.admin.service.transaction.Transaction; +import org.apache.nifi.admin.service.transaction.TransactionBuilder; +import org.apache.nifi.admin.service.transaction.TransactionException; +import org.apache.nifi.key.Key; +import org.apache.nifi.util.NiFiProperties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * + */ +public class StandardKeyService implements KeyService { + + private static final Logger logger = LoggerFactory.getLogger(StandardKeyService.class); + + private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private final Lock readLock = lock.readLock(); + private final Lock writeLock = lock.writeLock(); + + private TransactionBuilder transactionBuilder; + private NiFiProperties properties; + + @Override + public Key getKey(int id) { + Transaction transaction = null; + Key key = null; + + readLock.lock(); + try { + // start the transaction + transaction = transactionBuilder.start(); + + // get the key + GetKeyByIdAction addActions = new GetKeyByIdAction(id); + key = transaction.execute(addActions); + + // commit the transaction + transaction.commit(); + } catch (TransactionException | DataAccessException te) { + rollback(transaction); + throw new AdministrationException(te); + } catch (Throwable t) { + rollback(transaction); + throw t; + } finally { + closeQuietly(transaction); + readLock.unlock(); + } + + return key; + } + + @Override + public Key getOrCreateKey(String identity) { + Transaction transaction = null; + Key key = null; + + writeLock.lock(); + try { + // start the transaction + transaction = transactionBuilder.start(); + + // get or create a key + GetOrCreateKeyAction addActions = new GetOrCreateKeyAction(identity); + key = transaction.execute(addActions); + + // commit the transaction + transaction.commit(); + } catch (TransactionException | DataAccessException te) { + rollback(transaction); + throw new AdministrationException(te); + } catch (Throwable t) { + rollback(transaction); + throw t; + } finally { + closeQuietly(transaction); + writeLock.unlock(); + } + + return key; + } + + @Override + public void deleteKey(String identity) { + Transaction transaction = null; + + writeLock.lock(); + try { + // start the transaction + transaction = transactionBuilder.start(); + + // delete the keys + DeleteKeysAction deleteKeys = new DeleteKeysAction(identity); + transaction.execute(deleteKeys); + + // commit the transaction + transaction.commit(); + } catch (TransactionException | DataAccessException te) { + rollback(transaction); + throw new AdministrationException(te); + } catch (Throwable t) { + rollback(transaction); + throw t; + } finally { + closeQuietly(transaction); + writeLock.unlock(); + } + } + + private void rollback(final Transaction transaction) { + if (transaction != null) { + transaction.rollback(); + } + } + + private void closeQuietly(final Transaction transaction) { + if (transaction != null) { + try { + transaction.close(); + } catch (final IOException ioe) { + } + } + } + + public void setTransactionBuilder(TransactionBuilder transactionBuilder) { + this.transactionBuilder = transactionBuilder; + } + + public void setProperties(NiFiProperties properties) { + this.properties = properties; + } + +} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/impl/StandardUserService.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/impl/StandardUserService.java deleted file mode 100644 index c37a562f83..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/impl/StandardUserService.java +++ /dev/null @@ -1,731 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.impl; - -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.service.AccountDisabledException; -import org.apache.nifi.admin.service.AccountPendingException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.admin.service.UserService; -import org.apache.nifi.admin.service.action.AuthorizeDownloadAction; -import org.apache.nifi.admin.service.action.AuthorizeUserAction; -import org.apache.nifi.admin.service.action.DeleteKeysAction; -import org.apache.nifi.admin.service.action.DeleteUserAction; -import org.apache.nifi.admin.service.action.DisableUserAction; -import org.apache.nifi.admin.service.action.DisableUserGroupAction; -import org.apache.nifi.admin.service.action.FindUserByDnAction; -import org.apache.nifi.admin.service.action.FindUserByIdAction; -import org.apache.nifi.admin.service.action.GetKeyByIdAction; -import org.apache.nifi.admin.service.action.GetOrCreateKeyAction; -import org.apache.nifi.admin.service.action.GetUserGroupAction; -import org.apache.nifi.admin.service.action.GetUsersAction; -import org.apache.nifi.admin.service.action.HasPendingUserAccounts; -import org.apache.nifi.admin.service.action.InvalidateUserAccountAction; -import org.apache.nifi.admin.service.action.InvalidateUserGroupAccountsAction; -import org.apache.nifi.admin.service.action.RequestUserAccountAction; -import org.apache.nifi.admin.service.action.SeedUserAccountsAction; -import org.apache.nifi.admin.service.action.UpdateUserAction; -import org.apache.nifi.admin.service.action.UpdateUserGroupAction; -import org.apache.nifi.admin.service.action.UngroupUserAction; -import org.apache.nifi.admin.service.action.UngroupUserGroupAction; -import org.apache.nifi.admin.service.transaction.Transaction; -import org.apache.nifi.admin.service.transaction.TransactionBuilder; -import org.apache.nifi.admin.service.transaction.TransactionException; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.DownloadAuthorization; -import org.apache.nifi.key.Key; -import org.apache.nifi.user.NiFiUser; -import org.apache.nifi.user.NiFiUserGroup; -import org.apache.nifi.util.FormatUtils; -import org.apache.nifi.util.NiFiProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class StandardUserService implements UserService { - - private static final Logger logger = LoggerFactory.getLogger(StandardUserService.class); - - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - private final ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); - private final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); - - private TransactionBuilder transactionBuilder; - private NiFiProperties properties; - - /** - * Seed any users from the authority provider that are not already present. - */ - public void seedUserAccounts() { - // do not seed node's user cache. when/if the node disconnects its - // cache will be populated lazily (as needed) - if (properties.isNode()) { - return; - } - - Transaction transaction = null; - writeLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // seed the accounts - SeedUserAccountsAction seedUserAccounts = new SeedUserAccountsAction(); - transaction.execute(seedUserAccounts); - - // commit the transaction - transaction.commit(); - } catch (AdministrationException ae) { - rollback(transaction); - throw ae; - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - @Override - public NiFiUser createPendingUserAccount(String dn, String justification) { - Transaction transaction = null; - - writeLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // create the account request - RequestUserAccountAction requestUserAccount = new RequestUserAccountAction(dn, justification); - NiFiUser user = transaction.execute(requestUserAccount); - - // commit the transaction - transaction.commit(); - - // return the nifi user - return user; - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - @Override - public NiFiUserGroup updateGroup(final String group, final Set userIds, final Set authorities) { - Transaction transaction = null; - - writeLock.lock(); - try { - // if user ids have been specified, invalidate the user accounts before performing - // the desired updates. if case of an error, this will ensure that these users are - // authorized the next time the access the application - if (userIds != null) { - for (final String userId : userIds) { - invalidateUserAccount(userId); - } - } - - // start the transaction - transaction = transactionBuilder.start(); - - // set the authorities for each user in this group if specified - final UpdateUserGroupAction updateUserGroup = new UpdateUserGroupAction(group, userIds, authorities); - transaction.execute(updateUserGroup); - - // get all the users that are now in this group - final GetUserGroupAction getUserGroup = new GetUserGroupAction(group); - final NiFiUserGroup userGroup = transaction.execute(getUserGroup); - - // commit the transaction - transaction.commit(); - - return userGroup; - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - @Override - public void ungroupUser(String id) { - Transaction transaction = null; - - writeLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // ungroup the specified user - final UngroupUserAction ungroupUser = new UngroupUserAction(id); - transaction.execute(ungroupUser); - - // commit the transaction - transaction.commit(); - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - @Override - public void ungroup(String group) { - Transaction transaction = null; - - writeLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // ungroup the specified user - final UngroupUserGroupAction ungroupUserGroup = new UngroupUserGroupAction(group); - transaction.execute(ungroupUserGroup); - - // commit the transaction - transaction.commit(); - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - @Override - public NiFiUser checkAuthorization(String dn) { - Transaction transaction = null; - - writeLock.lock(); - try { - // create the connection - transaction = transactionBuilder.start(); - - // determine how long the cache is valid for - final int cacheSeconds; - try { - cacheSeconds = (int) FormatUtils.getTimeDuration(properties.getUserCredentialCacheDuration(), TimeUnit.SECONDS); - } catch (IllegalArgumentException iae) { - throw new AdministrationException("User credential cache duration is not configured correctly."); - } - - // attempt to authorize the user - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(dn, cacheSeconds); - NiFiUser user = transaction.execute(authorizeUser); - - // commit the transaction - transaction.commit(); - - // return the nifi user - return user; - } catch (DataAccessException | TransactionException dae) { - rollback(transaction); - throw new AdministrationException(dae); - } catch (AccountDisabledException | AccountPendingException ade) { - rollback(transaction); - throw ade; - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - @Override - public void deleteUser(String id) { - Transaction transaction = null; - - writeLock.lock(); - try { - // create the connection - transaction = transactionBuilder.start(); - - // delete the user - DeleteUserAction deleteUser = new DeleteUserAction(id); - transaction.execute(deleteUser); - - // commit the transaction - transaction.commit(); - } catch (DataAccessException | TransactionException dae) { - rollback(transaction); - throw new AdministrationException(dae); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - @Override - public NiFiUser disable(String id) { - Transaction transaction = null; - - writeLock.lock(); - try { - // create the connection - transaction = transactionBuilder.start(); - - // disable the user - DisableUserAction disableUser = new DisableUserAction(id); - NiFiUser user = transaction.execute(disableUser); - - // commit the transaction - transaction.commit(); - - // return the user - return user; - } catch (DataAccessException | TransactionException dae) { - rollback(transaction); - throw new AdministrationException(dae); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - @Override - public NiFiUserGroup disableGroup(String group) { - Transaction transaction = null; - - writeLock.lock(); - try { - // create the connection - transaction = transactionBuilder.start(); - - // disable the user - DisableUserGroupAction disableUser = new DisableUserGroupAction(group); - NiFiUserGroup userGroup = transaction.execute(disableUser); - - // commit the transaction - transaction.commit(); - - // return the user - return userGroup; - } catch (DataAccessException | TransactionException dae) { - rollback(transaction); - throw new AdministrationException(dae); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - @Override - public NiFiUser update(String id, Set authorities) { - Transaction transaction = null; - - // may be empty but not null - if (authorities == null) { - throw new IllegalArgumentException("The specified authorities cannot be null."); - } - - writeLock.lock(); - try { - // invalidate the user account in preparation for potential subsequent errors - invalidateUserAccount(id); - - // at this point the current user account has been invalidated so we will - // attempt to update the account. if any part fails we are assured the - // user will be need to be given approval before they access the system at - // a later time - // start the transaction - transaction = transactionBuilder.start(); - - // update the user authorities - UpdateUserAction setUserAuthorities = new UpdateUserAction(id, authorities); - NiFiUser user = transaction.execute(setUserAuthorities); - - // commit the transaction - transaction.commit(); - - // return the user - return user; - } catch (TransactionException | DataAccessException e) { - rollback(transaction); - throw new AdministrationException(e); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - /** - * Invalidates the user with the specified id. This is done to ensure a user account will need to be re-validated in case an error occurs while modifying a user account. This method should only be - * invoked from within a write lock. - * - * @param id user account identifier - */ - @Override - public void invalidateUserAccount(String id) { - Transaction transaction = null; - - writeLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // invalidate the user account - InvalidateUserAccountAction invalidateUserAccount = new InvalidateUserAccountAction(id); - transaction.execute(invalidateUserAccount); - - // commit the transaction - transaction.commit(); - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - @Override - public void invalidateUserGroupAccount(String group) { - Transaction transaction = null; - - writeLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // invalidate the user account - InvalidateUserGroupAccountsAction invalidateUserGroupAccounts = new InvalidateUserGroupAccountsAction(group); - transaction.execute(invalidateUserGroupAccounts); - - // commit the transaction - transaction.commit(); - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - // ----------------- - // read only methods - // ----------------- - @Override - public Boolean hasPendingUserAccount() { - Transaction transaction = null; - - readLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - final HasPendingUserAccounts hasPendingAccounts = new HasPendingUserAccounts(); - final Boolean hasPendingUserAccounts = transaction.execute(hasPendingAccounts); - - // commit the transaction - transaction.commit(); - - return hasPendingUserAccounts; - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - readLock.unlock(); - } - } - - @Override - public DownloadAuthorization authorizeDownload(final List dnChain, final Map attributes) { - Transaction transaction = null; - - readLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // authorize the download - AuthorizeDownloadAction authorizeDownload = new AuthorizeDownloadAction(dnChain, attributes); - DownloadAuthorization downloadAuthorization = transaction.execute(authorizeDownload); - - // commit the transaction - transaction.commit(); - - // return the authorization - return downloadAuthorization; - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - readLock.unlock(); - } - } - - @Override - public Collection getUsers() { - Transaction transaction = null; - - readLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // get all users - GetUsersAction getUsers = new GetUsersAction(); - Collection users = transaction.execute(getUsers); - - // commit the transaction - transaction.commit(); - - // return the users - return users; - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - readLock.unlock(); - } - } - - @Override - public NiFiUser getUserById(String id) { - Transaction transaction = null; - - readLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // return the desired user - FindUserByIdAction findUserById = new FindUserByIdAction(id); - NiFiUser user = transaction.execute(findUserById); - - // commit the transaction - transaction.commit(); - - // return the user - return user; - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - readLock.unlock(); - } - } - - @Override - public NiFiUser getUserByDn(String dn) { - Transaction transaction = null; - - readLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // return the desired user - FindUserByDnAction findUserByDn = new FindUserByDnAction(dn); - NiFiUser user = transaction.execute(findUserByDn); - - // commit the transaction - transaction.commit(); - - // return the user - return user; - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - readLock.unlock(); - } - } - - @Override - public Key getKey(int id) { - Transaction transaction = null; - Key key = null; - - readLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // get the key - GetKeyByIdAction addActions = new GetKeyByIdAction(id); - key = transaction.execute(addActions); - - // commit the transaction - transaction.commit(); - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - readLock.unlock(); - } - - return key; - } - - @Override - public Key getOrCreateKey(String identity) { - Transaction transaction = null; - Key key = null; - - writeLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // get or create a key - GetOrCreateKeyAction addActions = new GetOrCreateKeyAction(identity); - key = transaction.execute(addActions); - - // commit the transaction - transaction.commit(); - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - - return key; - } - - @Override - public void deleteKey(String identity) { - Transaction transaction = null; - - writeLock.lock(); - try { - // start the transaction - transaction = transactionBuilder.start(); - - // delete the keys - DeleteKeysAction deleteKeys = new DeleteKeysAction(identity); - transaction.execute(deleteKeys); - - // commit the transaction - transaction.commit(); - } catch (TransactionException | DataAccessException te) { - rollback(transaction); - throw new AdministrationException(te); - } catch (Throwable t) { - rollback(transaction); - throw t; - } finally { - closeQuietly(transaction); - writeLock.unlock(); - } - } - - private void rollback(final Transaction transaction) { - if (transaction != null) { - transaction.rollback(); - } - } - - private void closeQuietly(final Transaction transaction) { - if (transaction != null) { - try { - transaction.close(); - } catch (final IOException ioe) { - } - } - } - - public void setTransactionBuilder(TransactionBuilder transactionBuilder) { - this.transactionBuilder = transactionBuilder; - } - - public void setProperties(NiFiProperties properties) { - this.properties = properties; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/transaction/impl/StandardTransaction.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/transaction/impl/StandardTransaction.java index a3cfb5e3c0..1390768745 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/transaction/impl/StandardTransaction.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/transaction/impl/StandardTransaction.java @@ -16,19 +16,19 @@ */ package org.apache.nifi.admin.service.transaction.impl; -import java.io.IOException; -import java.sql.Connection; -import java.sql.SQLException; import org.apache.nifi.admin.RepositoryUtils; import org.apache.nifi.admin.dao.DAOFactory; import org.apache.nifi.admin.dao.impl.DAOFactoryImpl; import org.apache.nifi.admin.service.action.AdministrationAction; -import org.apache.nifi.admin.service.transaction.TransactionException; import org.apache.nifi.admin.service.transaction.Transaction; -import org.apache.nifi.authorization.AuthorityProvider; +import org.apache.nifi.admin.service.transaction.TransactionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; + /** * Transaction implementation that uses the specified SQL Connection and * AuthorityProvider. @@ -37,11 +37,9 @@ public class StandardTransaction implements Transaction { private static final Logger logger = LoggerFactory.getLogger(StandardTransaction.class); - private final AuthorityProvider authorityProvider; private Connection connection; - public StandardTransaction(AuthorityProvider authorityProvider, Connection connection) { - this.authorityProvider = authorityProvider; + public StandardTransaction(Connection connection) { this.connection = connection; } @@ -56,7 +54,7 @@ public class StandardTransaction implements Transaction { DAOFactory daoFactory = new DAOFactoryImpl(connection); // execute the specified action - return action.execute(daoFactory, authorityProvider); + return action.execute(daoFactory); } @Override diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/transaction/impl/StandardTransactionBuilder.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/transaction/impl/StandardTransactionBuilder.java index b6e5a30745..7d4a1fcc44 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/transaction/impl/StandardTransactionBuilder.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/service/transaction/impl/StandardTransactionBuilder.java @@ -22,7 +22,6 @@ import javax.sql.DataSource; import org.apache.nifi.admin.service.transaction.Transaction; import org.apache.nifi.admin.service.transaction.TransactionBuilder; import org.apache.nifi.admin.service.transaction.TransactionException; -import org.apache.nifi.authorization.AuthorityProvider; /** * @@ -30,7 +29,6 @@ import org.apache.nifi.authorization.AuthorityProvider; public class StandardTransactionBuilder implements TransactionBuilder { private DataSource dataSource; - private AuthorityProvider authorityProvider; @Override public Transaction start() throws TransactionException { @@ -40,7 +38,7 @@ public class StandardTransactionBuilder implements TransactionBuilder { connection.setAutoCommit(false); // create a new transaction - return new StandardTransaction(authorityProvider, connection); + return new StandardTransaction(connection); } catch (SQLException sqle) { throw new TransactionException(sqle.getMessage()); } @@ -50,8 +48,4 @@ public class StandardTransactionBuilder implements TransactionBuilder { public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } - - public void setAuthorityProvider(AuthorityProvider authorityProvider) { - this.authorityProvider = authorityProvider; - } } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/AuthorityProviderFactoryBean.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/AuthorityProviderFactoryBean.java deleted file mode 100644 index e1a02b8370..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/AuthorityProviderFactoryBean.java +++ /dev/null @@ -1,491 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.authorization.annotation.AuthorityProviderContext; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.IdentityAlreadyExistsException; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.authorization.exception.ProviderDestructionException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.authorization.generated.AuthorityProviderProperty; -import org.apache.nifi.authorization.generated.AuthorityProviders; -import org.apache.nifi.authorization.generated.Provider; -import org.apache.nifi.nar.ExtensionManager; -import org.apache.nifi.nar.NarCloseable; -import org.apache.nifi.util.NiFiProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.xml.sax.SAXException; - -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import java.io.File; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Factory bean for loading the configured authority provider. - */ -public class AuthorityProviderFactoryBean implements FactoryBean, ApplicationContextAware, DisposableBean, AuthorityProviderLookup { - - private static final Logger logger = LoggerFactory.getLogger(AuthorityProviderFactoryBean.class); - private static final String AUTHORITY_PROVIDERS_XSD = "/authority-providers.xsd"; - private static final String JAXB_GENERATED_PATH = "org.apache.nifi.authorization.generated"; - private static final JAXBContext JAXB_CONTEXT = initializeJaxbContext(); - - /** - * Load the JAXBContext. - */ - private static JAXBContext initializeJaxbContext() { - try { - return JAXBContext.newInstance(JAXB_GENERATED_PATH, AuthorityProviderFactoryBean.class.getClassLoader()); - } catch (JAXBException e) { - throw new RuntimeException("Unable to create JAXBContext."); - } - } - - private ApplicationContext applicationContext; - private AuthorityProvider authorityProvider; - private NiFiProperties properties; - private final Map authorityProviders = new HashMap<>(); - - @Override - public AuthorityProvider getAuthorityProvider(String identifier) { - return authorityProviders.get(identifier); - } - - @Override - public Object getObject() throws Exception { - if (authorityProvider == null) { - // look up the authority provider to use - final String authorityProviderIdentifier = properties.getProperty(NiFiProperties.SECURITY_USER_AUTHORITY_PROVIDER); - - // ensure the authority provider class name was specified - if (StringUtils.isBlank(authorityProviderIdentifier)) { - // if configured for ssl, the authority provider must be specified - if (properties.getSslPort() != null) { - throw new Exception("When running securely, the authority provider identifier must be specified in the nifi properties file."); - } - - // use a default provider... only allowable when running not securely - authorityProvider = createDefaultProvider(); - } else { - final AuthorityProviders authorityProviderConfiguration = loadAuthorityProvidersConfiguration(); - - // create each authority provider - for (final Provider provider : authorityProviderConfiguration.getProvider()) { - authorityProviders.put(provider.getIdentifier(), createAuthorityProvider(provider.getIdentifier(), provider.getClazz())); - } - - // configure each authority provider - for (final Provider provider : authorityProviderConfiguration.getProvider()) { - final AuthorityProvider instance = authorityProviders.get(provider.getIdentifier()); - instance.onConfigured(loadAuthorityProviderConfiguration(provider)); - } - - // get the authority provider instance - authorityProvider = getAuthorityProvider(authorityProviderIdentifier); - - // ensure it was found - if (authorityProvider == null) { - throw new Exception(String.format("The specified authority provider '%s' could not be found.", authorityProviderIdentifier)); - } - } - } - - return authorityProvider; - } - - private AuthorityProviders loadAuthorityProvidersConfiguration() throws Exception { - final File authorityProvidersConfigurationFile = properties.getAuthorityProviderConfiguraitonFile(); - - // load the users from the specified file - if (authorityProvidersConfigurationFile.exists()) { - try { - // find the schema - final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - final Schema schema = schemaFactory.newSchema(AuthorityProviders.class.getResource(AUTHORITY_PROVIDERS_XSD)); - - // attempt to unmarshal - final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); - unmarshaller.setSchema(schema); - final JAXBElement element = unmarshaller.unmarshal(new StreamSource(authorityProvidersConfigurationFile), AuthorityProviders.class); - return element.getValue(); - } catch (SAXException | JAXBException e) { - throw new Exception("Unable to load the authority provider configuration file at: " + authorityProvidersConfigurationFile.getAbsolutePath()); - } - } else { - throw new Exception("Unable to find the authority provider configuration file at " + authorityProvidersConfigurationFile.getAbsolutePath()); - } - } - - private AuthorityProvider createAuthorityProvider(final String identifier, final String authorityProviderClassName) throws Exception { - // get the classloader for the specified authority provider - final ClassLoader authorityProviderClassLoader = ExtensionManager.getClassLoader(authorityProviderClassName); - if (authorityProviderClassLoader == null) { - throw new Exception(String.format("The specified authority provider class '%s' is not known to this nifi.", authorityProviderClassName)); - } - - // get the current context classloader - final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); - - final AuthorityProvider instance; - try { - // set the appropriate class loader - Thread.currentThread().setContextClassLoader(authorityProviderClassLoader); - - // attempt to load the class - Class rawAuthorityProviderClass = Class.forName(authorityProviderClassName, true, authorityProviderClassLoader); - Class authorityProviderClass = rawAuthorityProviderClass.asSubclass(AuthorityProvider.class); - - // otherwise create a new instance - Constructor constructor = authorityProviderClass.getConstructor(); - instance = (AuthorityProvider) constructor.newInstance(); - - // method injection - performMethodInjection(instance, authorityProviderClass); - - // field injection - performFieldInjection(instance, authorityProviderClass); - - // call post construction lifecycle event - instance.initialize(new StandardAuthorityProviderInitializationContext(identifier, this)); - } finally { - if (currentClassLoader != null) { - Thread.currentThread().setContextClassLoader(currentClassLoader); - } - } - - return withNarLoader(instance); - } - - private AuthorityProviderConfigurationContext loadAuthorityProviderConfiguration(final Provider provider) { - final Map providerProperties = new HashMap<>(); - - for (final AuthorityProviderProperty property : provider.getProperty()) { - providerProperties.put(property.getName(), property.getValue()); - } - - return new StandardAuthorityProviderConfigurationContext(provider.getIdentifier(), providerProperties); - } - - private void performMethodInjection(final AuthorityProvider instance, final Class authorityProviderClass) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { - for (final Method method : authorityProviderClass.getMethods()) { - if (method.isAnnotationPresent(AuthorityProviderContext.class)) { - // make the method accessible - final boolean isAccessible = method.isAccessible(); - method.setAccessible(true); - - try { - final Class[] argumentTypes = method.getParameterTypes(); - - // look for setters (single argument) - if (argumentTypes.length == 1) { - final Class argumentType = argumentTypes[0]; - - // look for well known types - if (NiFiProperties.class.isAssignableFrom(argumentType)) { - // nifi properties injection - method.invoke(instance, properties); - } else if (ApplicationContext.class.isAssignableFrom(argumentType)) { - // spring application context injection - method.invoke(instance, applicationContext); - } - } - } finally { - method.setAccessible(isAccessible); - } - } - } - - final Class parentClass = authorityProviderClass.getSuperclass(); - if (parentClass != null && AuthorityProvider.class.isAssignableFrom(parentClass)) { - performMethodInjection(instance, parentClass); - } - } - - private void performFieldInjection(final AuthorityProvider instance, final Class authorityProviderClass) throws IllegalArgumentException, IllegalAccessException { - for (final Field field : authorityProviderClass.getDeclaredFields()) { - if (field.isAnnotationPresent(AuthorityProviderContext.class)) { - // make the method accessible - final boolean isAccessible = field.isAccessible(); - field.setAccessible(true); - - try { - // get the type - final Class fieldType = field.getType(); - - // only consider this field if it isn't set yet - if (field.get(instance) == null) { - // look for well known types - if (NiFiProperties.class.isAssignableFrom(fieldType)) { - // nifi properties injection - field.set(instance, properties); - } else if (ApplicationContext.class.isAssignableFrom(fieldType)) { - // spring application context injection - field.set(instance, applicationContext); - } - } - - } finally { - field.setAccessible(isAccessible); - } - } - } - - final Class parentClass = authorityProviderClass.getSuperclass(); - if (parentClass != null && AuthorityProvider.class.isAssignableFrom(parentClass)) { - performFieldInjection(instance, parentClass); - } - } - - /** - * @return a default provider to use when running unsecurely with no - * provider configured - */ - private AuthorityProvider createDefaultProvider() { - return new AuthorityProvider() { - @Override - public boolean doesDnExist(String dn) throws AuthorityAccessException { - return false; - } - - @Override - public Set getAuthorities(String dn) throws UnknownIdentityException, AuthorityAccessException { - return EnumSet.noneOf(Authority.class); - } - - @Override - public void setAuthorities(String dn, Set authorities) throws UnknownIdentityException, AuthorityAccessException { - } - - @Override - public Set getUsers(Authority authority) throws AuthorityAccessException { - return new HashSet<>(); - } - - @Override - public void revokeUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - } - - @Override - public void addUser(String dn, String group) throws IdentityAlreadyExistsException, AuthorityAccessException { - } - - @Override - public String getGroupForUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - return null; - } - - @Override - public void revokeGroup(String group) throws UnknownIdentityException, AuthorityAccessException { - } - - @Override - public void setUsersGroup(Set dn, String group) throws UnknownIdentityException, AuthorityAccessException { - } - - @Override - public void ungroupUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - } - - @Override - public void ungroup(String group) throws AuthorityAccessException { - } - - @Override - public DownloadAuthorization authorizeDownload(List dnChain, Map attributes) throws UnknownIdentityException, AuthorityAccessException { - return DownloadAuthorization.approved(); - } - - @Override - public void initialize(AuthorityProviderInitializationContext initializationContext) throws ProviderCreationException { - } - - @Override - public void onConfigured(AuthorityProviderConfigurationContext configurationContext) throws ProviderCreationException { - } - - @Override - public void preDestruction() throws ProviderDestructionException { - } - }; - } - - /** - * Decorates the base provider to ensure the nar context classloader is used - * when invoking the underlying methods. - * - * @param baseProvider base provider - * @return provider - */ - public AuthorityProvider withNarLoader(final AuthorityProvider baseProvider) { - return new AuthorityProvider() { - @Override - public boolean doesDnExist(String dn) throws AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - return baseProvider.doesDnExist(dn); - } - } - - @Override - public Set getAuthorities(String dn) throws UnknownIdentityException, AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - return baseProvider.getAuthorities(dn); - } - } - - @Override - public void setAuthorities(String dn, Set authorities) throws UnknownIdentityException, AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - baseProvider.setAuthorities(dn, authorities); - } - } - - @Override - public Set getUsers(Authority authority) throws AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - return baseProvider.getUsers(authority); - } - } - - @Override - public void revokeUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - baseProvider.revokeUser(dn); - } - } - - @Override - public void addUser(String dn, String group) throws IdentityAlreadyExistsException, AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - baseProvider.addUser(dn, group); - } - } - - @Override - public String getGroupForUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - return baseProvider.getGroupForUser(dn); - } - } - - @Override - public void revokeGroup(String group) throws UnknownIdentityException, AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - baseProvider.revokeGroup(group); - } - } - - @Override - public void setUsersGroup(Set dns, String group) throws UnknownIdentityException, AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - baseProvider.setUsersGroup(dns, group); - } - } - - @Override - public void ungroupUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - baseProvider.ungroupUser(dn); - } - } - - @Override - public void ungroup(String group) throws AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - baseProvider.ungroup(group); - } - } - - @Override - public DownloadAuthorization authorizeDownload(List dnChain, Map attributes) throws UnknownIdentityException, AuthorityAccessException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - return baseProvider.authorizeDownload(dnChain, attributes); - } - } - - @Override - public void initialize(AuthorityProviderInitializationContext initializationContext) throws ProviderCreationException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - baseProvider.initialize(initializationContext); - } - } - - @Override - public void onConfigured(AuthorityProviderConfigurationContext configurationContext) throws ProviderCreationException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - baseProvider.onConfigured(configurationContext); - } - } - - @Override - public void preDestruction() throws ProviderDestructionException { - try (final NarCloseable narCloseable = NarCloseable.withNarLoader()) { - baseProvider.preDestruction(); - } - } - }; - } - - @Override - public Class getObjectType() { - return AuthorityProvider.class; - } - - @Override - public boolean isSingleton() { - return true; - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - @Override - public void destroy() throws Exception { - if (authorityProvider != null) { - authorityProvider.preDestruction(); - } - } - - public void setProperties(NiFiProperties properties) { - this.properties = properties; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/AuthorizerFactoryBean.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/AuthorizerFactoryBean.java index 58caea9b37..cf35c15f5c 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/AuthorizerFactoryBean.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/AuthorizerFactoryBean.java @@ -21,7 +21,6 @@ import org.apache.nifi.authorization.annotation.AuthorizerContext; import org.apache.nifi.authorization.exception.AuthorizationAccessException; import org.apache.nifi.authorization.exception.AuthorizerCreationException; import org.apache.nifi.authorization.exception.AuthorizerDestructionException; -import org.apache.nifi.authorization.generated.AuthorityProviders; import org.apache.nifi.authorization.generated.Authorizers; import org.apache.nifi.authorization.generated.Property; import org.apache.nifi.nar.ExtensionManager; @@ -83,7 +82,7 @@ public class AuthorizerFactoryBean implements FactoryBean, DisposableBean, Autho public Object getObject() throws Exception { if (authorizer == null) { // look up the authorizer to use - final String authorizerIdentifier = properties.getProperty(NiFiProperties.SECURITY_USER_AUTHORITY_PROVIDER); + final String authorizerIdentifier = properties.getProperty(NiFiProperties.SECURITY_USER_AUTHORIZER); // ensure the authorizer class name was specified if (StringUtils.isBlank(authorizerIdentifier)) { @@ -122,14 +121,14 @@ public class AuthorizerFactoryBean implements FactoryBean, DisposableBean, Autho } private Authorizers loadAuthorizersConfiguration() throws Exception { - final File authorizersConfigurationFile = properties.getAuthorityProviderConfiguraitonFile(); + final File authorizersConfigurationFile = properties.getAuthorizerConfiguraitonFile(); // load the authorizers from the specified file if (authorizersConfigurationFile.exists()) { try { // find the schema final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - final Schema schema = schemaFactory.newSchema(AuthorityProviders.class.getResource(AUTHORIZERS_XSD)); + final Schema schema = schemaFactory.newSchema(Authorizers.class.getResource(AUTHORIZERS_XSD)); // attempt to unmarshal final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); @@ -221,7 +220,7 @@ public class AuthorizerFactoryBean implements FactoryBean, DisposableBean, Autho } final Class parentClass = authorizerClass.getSuperclass(); - if (parentClass != null && AuthorityProvider.class.isAssignableFrom(parentClass)) { + if (parentClass != null && Authorizer.class.isAssignableFrom(parentClass)) { performMethodInjection(instance, parentClass); } } @@ -253,7 +252,7 @@ public class AuthorizerFactoryBean implements FactoryBean, DisposableBean, Autho } final Class parentClass = authorizerClass.getSuperclass(); - if (parentClass != null && AuthorityProvider.class.isAssignableFrom(parentClass)) { + if (parentClass != null && Authorizer.class.isAssignableFrom(parentClass)) { performFieldInjection(instance, parentClass); } } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/StandardAuthorityProviderConfigurationContext.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/StandardAuthorityProviderConfigurationContext.java deleted file mode 100644 index 45b84c8f40..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/StandardAuthorityProviderConfigurationContext.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -/** - * - */ -public class StandardAuthorityProviderConfigurationContext implements AuthorityProviderConfigurationContext { - - private final String identifier; - private final Map properties; - - public StandardAuthorityProviderConfigurationContext(String identifier, Map properties) { - this.identifier = identifier; - this.properties = Collections.unmodifiableMap(new HashMap(properties)); - } - - @Override - public String getIdentifier() { - return identifier; - } - - @Override - public Map getProperties() { - return properties; - } - - @Override - public String getProperty(String property) { - return properties.get(property); - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/StandardAuthorityProviderInitializationContext.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/StandardAuthorityProviderInitializationContext.java deleted file mode 100644 index e4b16c4a94..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/authorization/StandardAuthorityProviderInitializationContext.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -/** - * - */ -public class StandardAuthorityProviderInitializationContext implements AuthorityProviderInitializationContext { - - private final String identifier; - private final AuthorityProviderLookup authorityProviderLookup; - - public StandardAuthorityProviderInitializationContext(String identifier, AuthorityProviderLookup authorityProviderLookup) { - this.identifier = identifier; - this.authorityProviderLookup = authorityProviderLookup; - } - - @Override - public String getIdentifier() { - return identifier; - } - - @Override - public AuthorityProviderLookup getAuthorityProviderLookup() { - return authorityProviderLookup; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/user/AccountStatus.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/user/AccountStatus.java deleted file mode 100644 index d7becf1b2b..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/user/AccountStatus.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.user; - -/** - * Represents the status of a user's account. - */ -public enum AccountStatus { - - ACTIVE, - PENDING, - DISABLED; - - /** - * Returns the matching status or null if the specified status does not - * match any statuses. - * - * @param rawStatus string form of status - * @return account status object - */ - public static AccountStatus valueOfStatus(String rawStatus) { - AccountStatus desiredStatus = null; - - for (AccountStatus status : values()) { - if (status.toString().equals(rawStatus)) { - desiredStatus = status; - break; - } - } - - return desiredStatus; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/user/NiFiUser.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/user/NiFiUser.java index 231b13366e..3a919ba53f 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/user/NiFiUser.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/user/NiFiUser.java @@ -17,121 +17,54 @@ package org.apache.nifi.user; import java.io.Serializable; -import java.util.Date; -import java.util.EnumSet; import java.util.Objects; -import java.util.Set; -import org.apache.nifi.authorization.Authority; -import org.apache.commons.lang3.StringUtils; /** * An NiFiUser. */ public class NiFiUser implements Serializable { - public static final String ANONYMOUS_USER_IDENTITY = "anonymous"; + public static final NiFiUser ANONYMOUS = new NiFiUser("anonymous"); - private String id; private String identity; private String userName; - private String userGroup; - private String justification; - - private Date creation; - private Date lastVerified; - private Date lastAccessed; - - private AccountStatus status; - private EnumSet authorities; private NiFiUser chain; - /* getters / setters */ - public Date getCreation() { - return creation; + public NiFiUser(String identity) { + this(identity, identity, null); } - public void setCreation(Date creation) { - this.creation = creation; + public NiFiUser(String identity, String userName) { + this(identity, userName, null); } + public NiFiUser(String identity, NiFiUser chain) { + this(identity, identity, chain); + } + + public NiFiUser(String identity, String userName, NiFiUser chain) { + this.identity = identity; + this.userName = userName; + this.chain = chain; + } + + /* getters / setters */ + public String getIdentity() { return identity; } - public void setIdentity(String identity) { - this.identity = identity; - } - public String getUserName() { return userName; } - public void setUserName(String userName) { - this.userName = userName; - } - - public String getUserGroup() { - return userGroup; - } - - public void setUserGroup(String userGroup) { - this.userGroup = userGroup; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getJustification() { - return justification; - } - - public void setJustification(String justification) { - this.justification = justification; - } - - public AccountStatus getStatus() { - return status; - } - - public void setStatus(AccountStatus status) { - this.status = status; - } - - public Date getLastVerified() { - return lastVerified; - } - - public void setLastVerified(Date lastVerified) { - this.lastVerified = lastVerified; - } - - public Date getLastAccessed() { - return lastAccessed; - } - - public void setLastAccessed(Date lastAccessed) { - this.lastAccessed = lastAccessed; - } - public NiFiUser getChain() { return chain; } - public void setChain(NiFiUser chain) { - this.chain = chain; - } - - public Set getAuthorities() { - if (authorities == null) { - authorities = EnumSet.noneOf(Authority.class); - } - return authorities; + public boolean isAnonymous() { + return this == ANONYMOUS; } @Override @@ -158,7 +91,7 @@ public class NiFiUser implements Serializable { @Override public String toString() { - return String.format("identity[%s], userName[%s], justification[%s], authorities[%s]", getIdentity(), getUserName(), getJustification(), StringUtils.join(getAuthorities(), ", ")); + return String.format("identity[%s], userName[%s]", getIdentity(), getUserName(), ", "); } } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/resources/nifi-administration-context.xml b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/resources/nifi-administration-context.xml index 3a4631423b..deec0739df 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/resources/nifi-administration-context.xml +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/resources/nifi-administration-context.xml @@ -18,41 +18,34 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> - - - - - - + - - + + - - + + - - - - - + + + + - + - - + - - + + diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/xsd/authority-providers.xsd b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/xsd/authority-providers.xsd deleted file mode 100644 index 1a5fe50512..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/xsd/authority-providers.xsd +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/AuthorizeUserActionTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/AuthorizeUserActionTest.java deleted file mode 100644 index 8d3c15a7e9..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/AuthorizeUserActionTest.java +++ /dev/null @@ -1,433 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Date; -import java.util.EnumSet; -import java.util.Set; -import org.apache.nifi.admin.dao.AuthorityDAO; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountDisabledException; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AccountPendingException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; -import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -/** - * - */ -public class AuthorizeUserActionTest { - - private static final String USER_ID_6 = "6"; - private static final String USER_ID_7 = "7"; - private static final String USER_ID_8 = "8"; - private static final String USER_ID_9 = "9"; - private static final String USER_ID_10 = "10"; - private static final String USER_ID_11 = "11"; - - private static final String USER_IDENTITY_1 = "authority access exception while searching for user"; - private static final String USER_IDENTITY_2 = "unknown user"; - private static final String USER_IDENTITY_3 = "user removed after checking existence"; - private static final String USER_IDENTITY_4 = "access exception getting authorities"; - private static final String USER_IDENTITY_5 = "error creating user account"; - private static final String USER_IDENTITY_6 = "create user general sequence"; - private static final String USER_IDENTITY_7 = "existing user requires verification"; - private static final String USER_IDENTITY_8 = "existing user does not require verification"; - private static final String USER_IDENTITY_9 = "existing pending user"; - private static final String USER_IDENTITY_10 = "existing disabled user"; - private static final String USER_IDENTITY_11 = "existing user is now unknown in the authority provider"; - - private DAOFactory daoFactory; - private UserDAO userDao; - private AuthorityDAO authorityDao; - private AuthorityProvider authorityProvider; - - @Before - public void setup() throws Exception { - // mock the user dao - userDao = Mockito.mock(UserDAO.class); - Mockito.doAnswer(new Answer() { - @Override - public NiFiUser answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String id = (String) args[0]; - - NiFiUser user = null; - if (USER_ID_7.equals(id)) { - user = new NiFiUser(); - user.setId(USER_ID_7); - user.setIdentity(USER_IDENTITY_7); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_MONITOR)); - } else if (USER_ID_8.equals(id)) { - user = new NiFiUser(); - user.setId(USER_ID_8); - user.setIdentity(USER_IDENTITY_8); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_MONITOR)); - user.setLastVerified(new Date()); - } else if (USER_ID_11.equals(id)) { - user = new NiFiUser(); - user.setId(USER_ID_11); - user.setIdentity(USER_IDENTITY_11); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_MONITOR)); - user.setStatus(AccountStatus.ACTIVE); - } - - return user; - } - }).when(userDao).findUserById(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public NiFiUser answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - - NiFiUser user = null; - switch (dn) { - case USER_IDENTITY_7: - user = new NiFiUser(); - user.setId(USER_ID_7); - user.setIdentity(USER_IDENTITY_7); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_MONITOR)); - break; - case USER_IDENTITY_8: - user = new NiFiUser(); - user.setId(USER_ID_8); - user.setIdentity(USER_IDENTITY_8); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_MONITOR)); - user.setLastVerified(new Date()); - break; - case USER_IDENTITY_9: - user = new NiFiUser(); - user.setId(USER_ID_9); - user.setIdentity(USER_IDENTITY_9); - user.setStatus(AccountStatus.PENDING); - break; - case USER_IDENTITY_10: - user = new NiFiUser(); - user.setId(USER_ID_10); - user.setIdentity(USER_IDENTITY_10); - user.setStatus(AccountStatus.DISABLED); - break; - case USER_IDENTITY_11: - user = new NiFiUser(); - user.setId(USER_ID_11); - user.setIdentity(USER_IDENTITY_11); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_MONITOR)); - user.setStatus(AccountStatus.ACTIVE); - break; - } - - return user; - } - }).when(userDao).findUserByDn(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - NiFiUser user = (NiFiUser) args[0]; - switch (user.getIdentity()) { - case USER_IDENTITY_5: - throw new DataAccessException(); - case USER_IDENTITY_6: - user.setId(USER_ID_6); - break; - } - - // do nothing - return null; - } - }).when(userDao).createUser(Mockito.any(NiFiUser.class)); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - NiFiUser user = (NiFiUser) args[0]; - - // do nothing - return null; - } - }).when(userDao).updateUser(Mockito.any(NiFiUser.class)); - - // mock the authority dao - authorityDao = Mockito.mock(AuthorityDAO.class); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - Set authorities = (Set) args[0]; - String id = (String) args[1]; - - // do nothing - return null; - } - }).when(authorityDao).createAuthorities(Mockito.anySetOf(Authority.class), Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - Set authorities = (Set) args[0]; - String id = (String) args[1]; - - // do nothing - return null; - } - }).when(authorityDao).deleteAuthorities(Mockito.anySetOf(Authority.class), Mockito.anyString()); - - // mock the dao factory - daoFactory = Mockito.mock(DAOFactory.class); - Mockito.when(daoFactory.getUserDAO()).thenReturn(userDao); - Mockito.when(daoFactory.getAuthorityDAO()).thenReturn(authorityDao); - - // mock the authority provider - authorityProvider = Mockito.mock(AuthorityProvider.class); - Mockito.doAnswer(new Answer() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - switch (dn) { - case USER_IDENTITY_1: - throw new AuthorityAccessException(StringUtils.EMPTY); - case USER_IDENTITY_2: - return false; - } - - return true; - } - }).when(authorityProvider).doesDnExist(Mockito.anyString()); - Mockito.doAnswer(new Answer>() { - @Override - public Set answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - Set authorities = EnumSet.noneOf(Authority.class); - switch (dn) { - case USER_IDENTITY_3: - throw new UnknownIdentityException(StringUtils.EMPTY); - case USER_IDENTITY_4: - throw new AuthorityAccessException(StringUtils.EMPTY); - case USER_IDENTITY_6: - authorities.add(Authority.ROLE_MONITOR); - break; - case USER_IDENTITY_7: - authorities.add(Authority.ROLE_DFM); - break; - case USER_IDENTITY_9: - throw new UnknownIdentityException(StringUtils.EMPTY); - case USER_IDENTITY_10: - throw new UnknownIdentityException(StringUtils.EMPTY); - case USER_IDENTITY_11: - throw new UnknownIdentityException(StringUtils.EMPTY); - } - - return authorities; - } - }).when(authorityProvider).getAuthorities(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - Set authorites = (Set) args[1]; - - // do nothing - return null; - } - }).when(authorityProvider).setAuthorities(Mockito.anyString(), Mockito.anySet()); - } - - /** - * Tests AuthorityAccessException in doesDnExist. - * - * @throws Exception ex - */ - @Test(expected = AdministrationException.class) - public void testAuthorityAccessExceptionInDoesDnExist() throws Exception { - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_1, 0); - authorizeUser.execute(daoFactory, authorityProvider); - } - - /** - * Test unknown user in the authority provider. - * - * @throws Exception ex - */ - @Test(expected = AccountNotFoundException.class) - public void testUnknownUser() throws Exception { - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_2, 0); - authorizeUser.execute(daoFactory, authorityProvider); - } - - /** - * Test a user thats been removed after checking their existence. - * - * @throws Exception ex - */ - @Test(expected = AccountNotFoundException.class) - public void testUserRemovedAfterCheckingExistence() throws Exception { - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_3, 0); - authorizeUser.execute(daoFactory, authorityProvider); - } - - /** - * Testing AuthorityAccessException when getting authorities. - * - * @throws Exception ex - */ - @Test(expected = AdministrationException.class) - public void testAuthorityAccessException() throws Exception { - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_4, 0); - authorizeUser.execute(daoFactory, authorityProvider); - } - - /** - * Testing DataAccessException while creating user accounts. - * - * @throws Exception ex - */ - @Test(expected = DataAccessException.class) - public void testErrorCreatingUserAccount() throws Exception { - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_5, 0); - authorizeUser.execute(daoFactory, authorityProvider); - } - - /** - * Tests the general case when a user account is created. - * - * @throws Exception ex - */ - @Test - public void testAccountCreation() throws Exception { - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_6, 0); - NiFiUser user = authorizeUser.execute(daoFactory, authorityProvider); - - // verify the user - Assert.assertEquals(USER_IDENTITY_6, user.getIdentity()); - Assert.assertEquals(1, user.getAuthorities().size()); - Assert.assertTrue(user.getAuthorities().contains(Authority.ROLE_MONITOR)); - - // verify interaction with dao and provider - Mockito.verify(userDao, Mockito.times(1)).createUser(user); - } - - /** - * Tests the general case when there is an existing user account that - * requires verification. - * - * @throws Exception ex - */ - @Test - public void testExistingUserRequiresVerification() throws Exception { - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_7, 0); - NiFiUser user = authorizeUser.execute(daoFactory, authorityProvider); - - // verify the user - Assert.assertEquals(USER_IDENTITY_7, user.getIdentity()); - Assert.assertEquals(1, user.getAuthorities().size()); - Assert.assertTrue(user.getAuthorities().contains(Authority.ROLE_DFM)); - - // verify interaction with dao and provider - Mockito.verify(userDao, Mockito.times(1)).updateUser(user); - Mockito.verify(authorityDao, Mockito.times(1)).createAuthorities(EnumSet.of(Authority.ROLE_DFM), USER_ID_7); - } - - /** - * Tests the general case when there is an existing user account that does - * not require verification. - * - * @throws Exception ex - */ - @Test - public void testExistingUserNoVerification() throws Exception { - // disabling verification by passing in a large cache duration - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_8, Integer.MAX_VALUE); - NiFiUser user = authorizeUser.execute(daoFactory, authorityProvider); - - // verify the user - Assert.assertEquals(USER_IDENTITY_8, user.getIdentity()); - Assert.assertEquals(1, user.getAuthorities().size()); - Assert.assertTrue(user.getAuthorities().contains(Authority.ROLE_MONITOR)); - - // verify interaction with dao and provider - Mockito.verify(userDao, Mockito.times(1)).updateUser(user); - Mockito.verify(authorityDao, Mockito.never()).createAuthorities(Mockito.anySet(), Mockito.eq(USER_ID_8)); - Mockito.verify(authorityDao, Mockito.never()).deleteAuthorities(Mockito.anySet(), Mockito.eq(USER_ID_8)); - } - - /** - * Tests existing users whose accounts are in a pending status. - * - * @throws Exception ex - */ - @Test(expected = AccountPendingException.class) - public void testExistingPendingUser() throws Exception { - // disabling verification by passing in a large cache duration - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_9, Integer.MAX_VALUE); - authorizeUser.execute(daoFactory, authorityProvider); - } - - /** - * Tests existing users whose accounts are in a disabled status. - * - * @throws Exception ex - */ - @Test(expected = AccountDisabledException.class) - public void testExistingDisabledUser() throws Exception { - // disabling verification by passing in a large cache duration - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_10, Integer.MAX_VALUE); - authorizeUser.execute(daoFactory, authorityProvider); - } - - /** - * Tests the general case where there is an active user that has been - * removed from the authority provider. - * - * @throws Exception ex - */ - @Test - public void testExistingActiveUserNotFoundInProvider() throws Exception { - try { - AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_IDENTITY_11, 0); - authorizeUser.execute(daoFactory, authorityProvider); - - Assert.fail(); - } catch (AccountDisabledException ade) { - ArgumentCaptor user = ArgumentCaptor.forClass(NiFiUser.class); - - // verify interaction with dao - Mockito.verify(userDao, Mockito.times(1)).updateUser(user.capture()); - - // verify user - Assert.assertEquals(AccountStatus.DISABLED, user.getValue().getStatus()); - } - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/CreateUserActionTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/CreateUserActionTest.java deleted file mode 100644 index e372781867..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/CreateUserActionTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.EnumSet; -import java.util.Set; -import org.apache.nifi.admin.dao.AuthorityDAO; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.user.NiFiUser; -import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -/** - * Test cases for creating a user. - */ -public class CreateUserActionTest { - - private final String USER_ID_2 = "2"; - private final String USER_ID_3 = "3"; - - private final String USER_IDENTITY_1 = "data access exception when creating user"; - private final String USER_IDENTITY_3 = "general create user case"; - - private DAOFactory daoFactory; - private UserDAO userDao; - private AuthorityDAO authorityDao; - - @Before - public void setup() throws Exception { - // mock the user dao - userDao = Mockito.mock(UserDAO.class); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - NiFiUser user = (NiFiUser) args[0]; - - if (USER_IDENTITY_1.equals(user.getIdentity())) { - throw new DataAccessException(); - } else if (USER_IDENTITY_3.equals(user.getIdentity())) { - user.setId(USER_ID_3); - } - - // do nothing - return null; - } - }).when(userDao).createUser(Mockito.any(NiFiUser.class)); - - // mock the authority dao - authorityDao = Mockito.mock(AuthorityDAO.class); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - Set authorities = (Set) args[0]; - String id = (String) args[1]; - - if (USER_ID_2.equals(id)) { - throw new DataAccessException(StringUtils.EMPTY); - } - - // do nothing - return null; - } - }).when(authorityDao).createAuthorities(Mockito.anySetOf(Authority.class), Mockito.anyString()); - - // mock the dao factory - daoFactory = Mockito.mock(DAOFactory.class); - Mockito.when(daoFactory.getUserDAO()).thenReturn(userDao); - Mockito.when(daoFactory.getAuthorityDAO()).thenReturn(authorityDao); - } - - /** - * Tests DataAccessExceptions that occur while creating user accounts. - * - * @throws Exception ex - */ - @Test(expected = DataAccessException.class) - public void testExceptionCreatingUser() throws Exception { - NiFiUser user = new NiFiUser(); - user.setIdentity(USER_IDENTITY_1); - - CreateUserAction createUser = new CreateUserAction(user); - createUser.execute(daoFactory, null); - } - - /** - * Tests DataAccessExceptions that occur while create user authorities. - * - * @throws Exception ex - */ - @Test(expected = DataAccessException.class) - public void testExceptionCreatingAuthoroties() throws Exception { - NiFiUser user = new NiFiUser(); - user.setId(USER_ID_2); - - CreateUserAction createUser = new CreateUserAction(user); - createUser.execute(daoFactory, null); - } - - /** - * General case for creating a user. - * - * @throws Exception ex - */ - @Test - public void testCreateUserAccount() throws Exception { - NiFiUser user = new NiFiUser(); - user.setIdentity(USER_IDENTITY_3); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_DFM, Authority.ROLE_ADMIN)); - - CreateUserAction createUser = new CreateUserAction(user); - createUser.execute(daoFactory, null); - - // verify the user - Assert.assertEquals(USER_ID_3, user.getId()); - - // verify interaction with dao - Mockito.verify(userDao, Mockito.times(1)).createUser(user); - Mockito.verify(authorityDao, Mockito.times(1)).createAuthorities(user.getAuthorities(), USER_ID_3); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/DisableUserActionTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/DisableUserActionTest.java deleted file mode 100644 index b5f0a7fcb2..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/DisableUserActionTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; -import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.admin.dao.KeyDAO; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -public class DisableUserActionTest { - - private static final String USER_ID_1 = "1"; - private static final String USER_ID_2 = "2"; - private static final String USER_ID_3 = "3"; - private static final String USER_ID_4 = "4"; - - private static final String USER_IDENTITY_3 = "authority access exception"; - private static final String USER_IDENTITY_4 = "general disable user case"; - - private DAOFactory daoFactory; - private UserDAO userDao; - private KeyDAO keyDao; - private AuthorityProvider authorityProvider; - - @Before - public void setup() throws Exception { - // mock the user dao - userDao = Mockito.mock(UserDAO.class); - Mockito.doAnswer(new Answer() { - @Override - public NiFiUser answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String id = (String) args[0]; - - NiFiUser user = null; - if (USER_ID_1.equals(id)) { - // leave user uninitialized - } else if (USER_ID_2.equals(id)) { - user = new NiFiUser(); - user.setId(id); - } else if (USER_ID_3.equals(id)) { - user = new NiFiUser(); - user.setId(id); - user.setIdentity(USER_IDENTITY_3); - } else if (USER_ID_4.equals(id)) { - user = new NiFiUser(); - user.setId(id); - user.setIdentity(USER_IDENTITY_4); - user.setStatus(AccountStatus.ACTIVE); - } - return user; - } - }).when(userDao).findUserById(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - NiFiUser user = (NiFiUser) args[0]; - - if (USER_ID_2.equals(user.getId())) { - throw new DataAccessException(StringUtils.EMPTY); - } - - // do nothing - return null; - } - }).when(userDao).updateUser(Mockito.any(NiFiUser.class)); - - // mock the dao factory - keyDao = Mockito.mock(KeyDAO.class); - Mockito.doNothing().when(keyDao).deleteKeys(Matchers.anyString()); - - // mock the dao factory - daoFactory = Mockito.mock(DAOFactory.class); - Mockito.when(daoFactory.getUserDAO()).thenReturn(userDao); - Mockito.when(daoFactory.getKeyDAO()).thenReturn(keyDao); - - // mock the authority provider - authorityProvider = Mockito.mock(AuthorityProvider.class); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - - if (USER_IDENTITY_3.equals(dn)) { - throw new AuthorityAccessException(StringUtils.EMPTY); - } - - // do nothing - return null; - } - }).when(authorityProvider).revokeUser(Mockito.anyString()); - } - - /** - * Tests the case when the user account is unknown. - * - * @throws Exception ex - */ - @Test(expected = AccountNotFoundException.class) - public void testUnknownUserAccount() throws Exception { - DisableUserAction disableUser = new DisableUserAction(USER_ID_1); - disableUser.execute(daoFactory, authorityProvider); - } - - /** - * Tests the case when a DataAccessException is thrown by the userDao. - * - * @throws Exception ex - */ - @Test(expected = DataAccessException.class) - public void testDataAccessExceptionInUserDao() throws Exception { - DisableUserAction disableUser = new DisableUserAction(USER_ID_2); - disableUser.execute(daoFactory, authorityProvider); - } - - /** - * Tests the case when a AuthorityAccessException is thrown by the provider. - * - * @throws Exception ex - */ - @Test(expected = AdministrationException.class) - public void testAuthorityAccessExceptionInProvider() throws Exception { - DisableUserAction disableUser = new DisableUserAction(USER_ID_3); - disableUser.execute(daoFactory, authorityProvider); - } - - /** - * Tests the general case when the user is disabled. - * - * @throws Exception ex - */ - @Test - public void testDisableUser() throws Exception { - DisableUserAction disableUser = new DisableUserAction(USER_ID_4); - NiFiUser user = disableUser.execute(daoFactory, authorityProvider); - - // verify the user - Assert.assertEquals(USER_ID_4, user.getId()); - Assert.assertEquals(USER_IDENTITY_4, user.getIdentity()); - Assert.assertEquals(AccountStatus.DISABLED, user.getStatus()); - - // verify the interaction with the dao and provider - Mockito.verify(userDao, Mockito.times(1)).updateUser(user); - Mockito.verify(authorityProvider, Mockito.times(1)).revokeUser(USER_IDENTITY_4); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/InvalidateUserAccountActionTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/InvalidateUserAccountActionTest.java deleted file mode 100644 index cffd280e01..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/InvalidateUserAccountActionTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Date; -import org.junit.Assert; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.user.NiFiUser; -import org.apache.commons.lang3.StringUtils; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -/** - * Test case for InvalidateUserAccountAction. - */ -public class InvalidateUserAccountActionTest { - - private static final String USER_ID_1 = "1"; - private static final String USER_ID_2 = "2"; - private static final String USER_ID_3 = "3"; - - private DAOFactory daoFactory; - private UserDAO userDao; - - @Before - public void setup() throws Exception { - // mock the user dao - userDao = Mockito.mock(UserDAO.class); - Mockito.doAnswer(new Answer() { - @Override - public NiFiUser answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String id = (String) args[0]; - - NiFiUser user = null; - if (USER_ID_1.equals(id)) { - // leave uninitialized - } else if (USER_ID_2.equals(id)) { - user = new NiFiUser(); - user.setId(USER_ID_2); - } else if (USER_ID_3.equals(id)) { - user = new NiFiUser(); - user.setId(USER_ID_3); - user.setLastVerified(new Date()); - } - return user; - } - }).when(userDao).findUserById(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - NiFiUser user = (NiFiUser) args[0]; - - if (USER_ID_2.equals(user.getId())) { - throw new DataAccessException(StringUtils.EMPTY); - } - - // do nothing - return null; - } - }).when(userDao).updateUser(Mockito.any(NiFiUser.class)); - - // mock the dao factory - daoFactory = Mockito.mock(DAOFactory.class); - Mockito.when(daoFactory.getUserDAO()).thenReturn(userDao); - } - - @Test(expected = AccountNotFoundException.class) - public void testAccountNotFoundException() throws Exception { - InvalidateUserAccountAction invalidateUserAccount = new InvalidateUserAccountAction(USER_ID_1); - invalidateUserAccount.execute(daoFactory, null); - } - - /** - * Tests when a data access exception occurs when updating the user record. - * - * @throws Exception ex - */ - @Test(expected = DataAccessException.class) - public void testDataAccessException() throws Exception { - InvalidateUserAccountAction invalidateUserAccount = new InvalidateUserAccountAction(USER_ID_2); - invalidateUserAccount.execute(daoFactory, null); - } - - /** - * Tests the general case of invalidating a user. - * - * @throws Exception ex - */ - @Test - public void testInvalidateUser() throws Exception { - InvalidateUserAccountAction invalidateUserAccount = new InvalidateUserAccountAction(USER_ID_3); - invalidateUserAccount.execute(daoFactory, null); - - // verify the interaction with the dao - ArgumentCaptor userCaptor = ArgumentCaptor.forClass(NiFiUser.class); - Mockito.verify(userDao, Mockito.times(1)).updateUser(userCaptor.capture()); - - // verify the user - NiFiUser user = userCaptor.getValue(); - Assert.assertEquals(USER_ID_3, user.getId()); - Assert.assertNull(user.getLastVerified()); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/RequestUserAccountActionTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/RequestUserAccountActionTest.java deleted file mode 100644 index 7bc863b20f..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/RequestUserAccountActionTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.DataAccessException; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; -import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -/** - * Test case for RequestUserAccountAction. - */ -public class RequestUserAccountActionTest { - - private static final String USER_ID_3 = "3"; - - private static final String USER_IDENTITY_1 = "existing user account"; - private static final String USER_IDENTITY_2 = "data access exception"; - private static final String USER_IDENTITY_3 = "new account request"; - - private DAOFactory daoFactory; - private UserDAO userDao; - - @Before - public void setup() throws Exception { - // mock the user dao - userDao = Mockito.mock(UserDAO.class); - Mockito.doAnswer(new Answer() { - @Override - public NiFiUser answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - - NiFiUser user = null; - if (USER_IDENTITY_1.equals(dn)) { - user = new NiFiUser(); - } - return user; - } - }).when(userDao).findUserByDn(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - NiFiUser user = (NiFiUser) args[0]; - switch (user.getIdentity()) { - case USER_IDENTITY_2: - throw new DataAccessException(); - case USER_IDENTITY_3: - user.setId(USER_ID_3); - break; - } - - // do nothing - return null; - } - }).when(userDao).createUser(Mockito.any(NiFiUser.class)); - - // mock the dao factory - daoFactory = Mockito.mock(DAOFactory.class); - Mockito.when(daoFactory.getUserDAO()).thenReturn(userDao); - } - - /** - * Tests when a user account already exists. - * - * @throws Exception ex - */ - @Test(expected = IllegalArgumentException.class) - public void testExistingAccount() throws Exception { - RequestUserAccountAction requestUserAccount = new RequestUserAccountAction(USER_IDENTITY_1, StringUtils.EMPTY); - requestUserAccount.execute(daoFactory, null); - } - - /** - * Tests when a DataAccessException occurs while saving the new account - * request. - * - * @throws Exception ex - */ - @Test(expected = DataAccessException.class) - public void testDataAccessException() throws Exception { - RequestUserAccountAction requestUserAccount = new RequestUserAccountAction(USER_IDENTITY_2, StringUtils.EMPTY); - requestUserAccount.execute(daoFactory, null); - } - - /** - * Tests the general case for requesting a new user account. - * - * @throws Exception ex - */ - @Test - public void testRequestUserAccountAction() throws Exception { - RequestUserAccountAction requestUserAccount = new RequestUserAccountAction(USER_IDENTITY_3, StringUtils.EMPTY); - NiFiUser user = requestUserAccount.execute(daoFactory, null); - - // verfiy the user - Assert.assertEquals(USER_ID_3, user.getId()); - Assert.assertEquals(USER_IDENTITY_3, user.getIdentity()); - Assert.assertEquals(AccountStatus.PENDING, user.getStatus()); - - // verify interaction with dao - Mockito.verify(userDao, Mockito.times(1)).createUser(user); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/SeedUserAccountsActionTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/SeedUserAccountsActionTest.java deleted file mode 100644 index 58db56a08b..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/SeedUserAccountsActionTest.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Set; -import org.apache.nifi.admin.dao.AuthorityDAO; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; -import org.hamcrest.Matcher; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentMatcher; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -/** - * - */ -public class SeedUserAccountsActionTest { - - private static final String USER_ID_1 = "1"; - private static final String USER_ID_2 = "2"; - private static final String USER_ID_3 = "3"; - private static final String USER_ID_4 = "4"; - - private static final String USER_IDENTITY_1 = "user 1 - active user - remove monitor and operator, add dfm"; - private static final String USER_IDENTITY_2 = "user 2 - active user - no action"; - private static final String USER_IDENTITY_3 = "user 3 - pending user - add operator"; - private static final String USER_IDENTITY_4 = "user 4 - new user - add monitor"; - - private DAOFactory daoFactory; - private UserDAO userDao; - private AuthorityDAO authorityDao; - private AuthorityProvider authorityProvider; - - @Before - public void setup() throws Exception { - // mock the user dao - userDao = Mockito.mock(UserDAO.class); - Mockito.doAnswer(new Answer() { - @Override - public NiFiUser answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String id = (String) args[0]; - - NiFiUser user = null; - if (USER_ID_1.equals(id)) { - user = new NiFiUser(); - user.setId(USER_ID_1); - user.setIdentity(USER_IDENTITY_1); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_MONITOR)); - user.setStatus(AccountStatus.ACTIVE); - } else if (USER_ID_2.equals(id)) { - user = new NiFiUser(); - user.setId(USER_ID_2); - user.setIdentity(USER_IDENTITY_2); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_ADMIN)); - user.setStatus(AccountStatus.ACTIVE); - } else if (USER_ID_3.equals(id)) { - user = new NiFiUser(); - user.setId(USER_ID_3); - user.setIdentity(USER_IDENTITY_3); - user.setStatus(AccountStatus.PENDING); - } - return user; - } - }).when(userDao).findUserById(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public NiFiUser answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - - NiFiUser user = null; - if (USER_IDENTITY_1.equals(dn)) { - user = new NiFiUser(); - user.setId(USER_ID_1); - user.setIdentity(USER_IDENTITY_1); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_MONITOR)); - user.setStatus(AccountStatus.ACTIVE); - } else if (USER_IDENTITY_2.equals(dn)) { - user = new NiFiUser(); - user.setId(USER_ID_2); - user.setIdentity(USER_IDENTITY_2); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_ADMIN)); - user.setStatus(AccountStatus.ACTIVE); - } else if (USER_IDENTITY_3.equals(dn)) { - user = new NiFiUser(); - user.setId(USER_ID_3); - user.setIdentity(USER_IDENTITY_3); - user.setStatus(AccountStatus.PENDING); - } - return user; - } - }).when(userDao).findUserByDn(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - NiFiUser user = (NiFiUser) args[0]; - - if (USER_IDENTITY_4.equals(user.getIdentity())) { - user.setId(USER_ID_4); - } - - return null; - } - }).when(userDao).createUser(Mockito.any(NiFiUser.class)); - - // mock the authority dao - authorityDao = Mockito.mock(AuthorityDAO.class); - - // mock the authority provider - authorityProvider = Mockito.mock(AuthorityProvider.class); - Mockito.doAnswer(new Answer>() { - @Override - public Set answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - Authority role = (Authority) args[0]; - - Set users = new HashSet<>(); - if (Authority.ROLE_DFM.equals(role)) { - users.add(USER_IDENTITY_1); - } else if (Authority.ROLE_ADMIN.equals(role)) { - users.add(USER_IDENTITY_2); - } else if (Authority.ROLE_PROXY.equals(role)) { - users.add(USER_IDENTITY_3); - } else if (Authority.ROLE_MONITOR.equals(role)) { - users.add(USER_IDENTITY_4); - } - return users; - } - }).when(authorityProvider).getUsers(Mockito.any(Authority.class)); - Mockito.doAnswer(new Answer>() { - @Override - public Set answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - - Set authorities = EnumSet.noneOf(Authority.class); - switch (dn) { - case USER_IDENTITY_1: - authorities.add(Authority.ROLE_DFM); - break; - case USER_IDENTITY_2: - authorities.add(Authority.ROLE_ADMIN); - break; - case USER_IDENTITY_3: - authorities.add(Authority.ROLE_PROXY); - break; - case USER_IDENTITY_4: - authorities.add(Authority.ROLE_MONITOR); - break; - } - return authorities; - } - }).when(authorityProvider).getAuthorities(Mockito.anyString()); - - // mock the dao factory - daoFactory = Mockito.mock(DAOFactory.class); - Mockito.when(daoFactory.getUserDAO()).thenReturn(userDao); - Mockito.when(daoFactory.getAuthorityDAO()).thenReturn(authorityDao); - } - - /** - * Tests seeding the user accounts. - * - * @throws Exception ex - */ - @Test - public void testSeedUsers() throws Exception { - SeedUserAccountsAction seedUserAccounts = new SeedUserAccountsAction(); - seedUserAccounts.execute(daoFactory, authorityProvider); - - // matcher for user 1 - Matcher matchesUser1 = new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - NiFiUser user = (NiFiUser) argument; - return USER_ID_1.equals(user.getId()); - } - }; - - // verify user 1 - active existing user - remove monitor, operator, add dfm - Mockito.verify(userDao, Mockito.times(1)).updateUser(Mockito.argThat(matchesUser1)); - Mockito.verify(userDao, Mockito.never()).createUser(Mockito.argThat(matchesUser1)); - Mockito.verify(authorityDao, Mockito.times(1)).createAuthorities(EnumSet.of(Authority.ROLE_DFM), USER_ID_1); - - // matcher for user 2 - Matcher matchesUser2 = new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - NiFiUser user = (NiFiUser) argument; - return USER_ID_2.equals(user.getId()); - } - }; - - // verify user 2 - active existing user - no actions - Mockito.verify(userDao, Mockito.times(1)).updateUser(Mockito.argThat(matchesUser2)); - Mockito.verify(userDao, Mockito.never()).createUser(Mockito.argThat(matchesUser2)); - Mockito.verify(authorityDao, Mockito.never()).createAuthorities(Mockito.anySet(), Mockito.eq(USER_ID_2)); - Mockito.verify(authorityDao, Mockito.never()).deleteAuthorities(Mockito.anySet(), Mockito.eq(USER_ID_2)); - - // matchers for user 3 - Matcher matchesPendingUser3 = new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - NiFiUser user = (NiFiUser) argument; - return USER_ID_3.equals(user.getId()) && AccountStatus.ACTIVE.equals(user.getStatus()); - } - }; - Matcher matchesUser3 = new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - NiFiUser user = (NiFiUser) argument; - return USER_ID_3.equals(user.getId()); - } - }; - - // verify user 3 - pending user - add operator - Mockito.verify(userDao, Mockito.times(1)).updateUser(Mockito.argThat(matchesPendingUser3)); - Mockito.verify(userDao, Mockito.never()).createUser(Mockito.argThat(matchesUser3)); - Mockito.verify(authorityDao, Mockito.times(1)).createAuthorities(EnumSet.of(Authority.ROLE_PROXY), USER_ID_3); - Mockito.verify(authorityDao, Mockito.never()).deleteAuthorities(Mockito.anySet(), Mockito.eq(USER_ID_3)); - - // matcher for user 4 - Matcher matchesUser4 = new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - NiFiUser user = (NiFiUser) argument; - return USER_ID_4.equals(user.getId()); - } - }; - - // verify user 4 - new user - add monitor - Mockito.verify(userDao, Mockito.never()).updateUser(Mockito.argThat(matchesUser4)); - Mockito.verify(userDao, Mockito.times(1)).createUser(Mockito.argThat(matchesUser4)); - Mockito.verify(authorityDao, Mockito.times(1)).createAuthorities(EnumSet.of(Authority.ROLE_MONITOR), USER_ID_4); - Mockito.verify(authorityDao, Mockito.never()).deleteAuthorities(Mockito.anySet(), Mockito.eq(USER_ID_4)); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/SetUserAuthoritiesActionTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/SetUserAuthoritiesActionTest.java deleted file mode 100644 index 5effdbba8a..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/test/java/org/apache/nifi/admin/service/action/SetUserAuthoritiesActionTest.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.admin.service.action; - -import java.util.Collections; -import java.util.EnumSet; -import java.util.Set; -import org.apache.nifi.admin.dao.AuthorityDAO; -import org.apache.nifi.admin.dao.DAOFactory; -import org.apache.nifi.admin.dao.UserDAO; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.user.AccountStatus; -import org.apache.nifi.user.NiFiUser; -import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -/** - * Test case for SetUserAuthoritiesAction. - */ -public class SetUserAuthoritiesActionTest { - - private static final String USER_ID_1 = "1"; - private static final String USER_ID_2 = "2"; - private static final String USER_ID_3 = "3"; - - private static final String USER_IDENTITY_2 = "user 2"; - private static final String USER_IDENTITY_3 = "user 3"; - - private DAOFactory daoFactory; - private UserDAO userDao; - private AuthorityDAO authorityDao; - private AuthorityProvider authorityProvider; - - @Before - public void setup() throws Exception { - // mock the user dao - userDao = Mockito.mock(UserDAO.class); - Mockito.doAnswer(new Answer() { - @Override - public NiFiUser answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String id = (String) args[0]; - - NiFiUser user = null; - if (USER_ID_1.equals(id)) { - // leave user uninitialized - } else if (USER_ID_2.equals(id)) { - user = new NiFiUser(); - user.setId(USER_ID_2); - user.setIdentity(USER_IDENTITY_2); - } else if (USER_ID_3.equals(id)) { - user = new NiFiUser(); - user.setId(USER_ID_3); - user.setIdentity(USER_IDENTITY_3); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_MONITOR)); - user.setStatus(AccountStatus.ACTIVE); - } - return user; - } - }).when(userDao).findUserById(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public NiFiUser answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - - NiFiUser user = null; - if (USER_IDENTITY_3.equals(dn)) { - user = new NiFiUser(); - user.setId(USER_ID_3); - user.setIdentity(USER_IDENTITY_3); - user.getAuthorities().addAll(EnumSet.of(Authority.ROLE_MONITOR)); - user.setStatus(AccountStatus.ACTIVE); - } - return user; - } - }).when(userDao).findUserByDn(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - NiFiUser user = (NiFiUser) args[0]; - - // do nothing - return null; - } - }).when(userDao).updateUser(Mockito.any(NiFiUser.class)); - - // mock the authority dao - authorityDao = Mockito.mock(AuthorityDAO.class); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - Set authorities = (Set) args[0]; - String id = (String) args[1]; - - // do nothing - return null; - } - }).when(authorityDao).createAuthorities(Mockito.anySetOf(Authority.class), Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - Set authorities = (Set) args[0]; - String id = (String) args[1]; - - // do nothing - return null; - } - }).when(authorityDao).deleteAuthorities(Mockito.anySetOf(Authority.class), Mockito.anyString()); - - // mock the dao factory - daoFactory = Mockito.mock(DAOFactory.class); - Mockito.when(daoFactory.getUserDAO()).thenReturn(userDao); - Mockito.when(daoFactory.getAuthorityDAO()).thenReturn(authorityDao); - - // mock the authority provider - authorityProvider = Mockito.mock(AuthorityProvider.class); - Mockito.doAnswer(new Answer>() { - @Override - public Set answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - - Set authorities = EnumSet.noneOf(Authority.class); - if (USER_IDENTITY_3.equals(dn)) { - authorities.add(Authority.ROLE_DFM); - } - - return authorities; - } - }).when(authorityProvider).getAuthorities(Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String dn = (String) args[0]; - Set authorites = (Set) args[1]; - - if (USER_IDENTITY_2.equals(dn)) { - throw new AuthorityAccessException(StringUtils.EMPTY); - } - - // do nothing - return null; - } - }).when(authorityProvider).setAuthorities(Mockito.anyString(), Mockito.anySet()); - } - - /** - * Test activating an unknown user account. User accounts are unknown then - * there is no pending account for the user. - * - * @throws Exception ex - */ - @Test(expected = AccountNotFoundException.class) - public void testUnknownUser() throws Exception { - UpdateUserAction setUserAuthorities = new UpdateUserAction(USER_ID_1, Collections.EMPTY_SET); - setUserAuthorities.execute(daoFactory, authorityProvider); - } - - /** - * Testing case then an AuthorityAccessException occurs while setting a - * users authorities. - * - * @throws Exception ex - */ - @Test(expected = AdministrationException.class) - public void testAuthorityAccessException() throws Exception { - UpdateUserAction setUserAuthorities = new UpdateUserAction(USER_ID_2, Collections.EMPTY_SET); - setUserAuthorities.execute(daoFactory, authorityProvider); - } - - /** - * Tests general case of setting user authorities. - * - * @throws Exception ex - */ - @Test - public void testSetAuthorities() throws Exception { - UpdateUserAction setUserAuthorities = new UpdateUserAction(USER_ID_3, EnumSet.of(Authority.ROLE_ADMIN)); - NiFiUser user = setUserAuthorities.execute(daoFactory, authorityProvider); - - // verify user - Assert.assertEquals(USER_ID_3, user.getId()); - Assert.assertEquals(1, user.getAuthorities().size()); - Assert.assertTrue(user.getAuthorities().contains(Authority.ROLE_ADMIN)); - - // verify interaction with dao - Mockito.verify(userDao, Mockito.times(1)).updateUser(user); - Mockito.verify(authorityDao, Mockito.times(1)).createAuthorities(EnumSet.of(Authority.ROLE_ADMIN), USER_ID_3); - - Set authoritiesAddedToProvider = EnumSet.of(Authority.ROLE_ADMIN); - - // verify interaction with provider - Mockito.verify(authorityProvider, Mockito.times(1)).setAuthorities(USER_IDENTITY_3, authoritiesAddedToProvider); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RevisionDTO.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RevisionDTO.java index c8ef843e73..200c9548c3 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RevisionDTO.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RevisionDTO.java @@ -18,6 +18,7 @@ package org.apache.nifi.web.api.dto; import com.wordnik.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlType; +import java.util.UUID; /** * Current revision for this NiFi. @@ -41,6 +42,9 @@ public class RevisionDTO { + "nature of requests/responses this was implemented to allow the client to make numerous requests without having to wait for the previous response to come back" ) public String getClientId() { + if (clientId == null || clientId.trim().isEmpty()) { + clientId = UUID.randomUUID().toString(); + } return clientId; } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/status/ControllerStatusDTO.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/status/ControllerStatusDTO.java index 03e2124b60..cec51e5c7f 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/status/ControllerStatusDTO.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/status/ControllerStatusDTO.java @@ -38,8 +38,6 @@ public class ControllerStatusDTO implements Cloneable { private Integer connectedNodeCount = 0; private Integer totalNodeCount = 0; - private Boolean hasPendingAccounts; - private Integer runningCount = 0; private Integer stoppedCount = 0; private Integer invalidCount = 0; @@ -126,18 +124,6 @@ public class ControllerStatusDTO implements Cloneable { this.reportingTaskBulletins = reportingTaskBulletins; } - /** - * @return whether or not there are pending user requests - */ - @ApiModelProperty("Whether there are any pending user account requests.") - public Boolean getHasPendingAccounts() { - return hasPendingAccounts; - } - - public void setHasPendingAccounts(Boolean hasPendingAccounts) { - this.hasPendingAccounts = hasPendingAccounts; - } - /** * @return number of running components in this controller */ @@ -256,7 +242,6 @@ public class ControllerStatusDTO implements Cloneable { other.setConnectedNodes(getConnectedNodes()); other.setConnectedNodeCount(getConnectedNodeCount()); other.setTotalNodeCount(getTotalNodeCount()); - other.setHasPendingAccounts(getHasPendingAccounts()); other.setRunningCount(getRunningCount()); other.setStoppedCount(getStoppedCount()); other.setInvalidCount(getInvalidCount()); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/Entity.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/Entity.java index ad3a7dee40..13c7a70fa9 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/Entity.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/Entity.java @@ -35,7 +35,11 @@ public class Entity { value = "The revision for this request/response. The revision is required for any mutable flow requests and is included in all responses." ) public RevisionDTO getRevision() { - return revision; + if (revision == null) { + return new RevisionDTO(); + } else { + return revision; + } } public void setRevision(RevisionDTO revision) { diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/GetGroupForUserMessage.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/UpdateControllerServiceReferenceRequestEntity.java similarity index 50% rename from nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/GetGroupForUserMessage.java rename to nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/UpdateControllerServiceReferenceRequestEntity.java index 72a6af59aa..0b2230e4c1 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/GetGroupForUserMessage.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/UpdateControllerServiceReferenceRequestEntity.java @@ -14,41 +14,41 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.nifi.cluster.authorization.protocol.message; +package org.apache.nifi.web.api.entity; + +import com.wordnik.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlRootElement; /** + * A serialized representation of this class can be placed in the entity body of a request to the API. */ -@XmlRootElement(name = "getGroupForUserMessage") -public class GetGroupForUserMessage extends ProtocolMessage { +@XmlRootElement(name = "updateControllerServiceReferenceRequestEntity") +public class UpdateControllerServiceReferenceRequestEntity extends Entity { - private String dn; + private String id; + private String state; - private String response; - - public GetGroupForUserMessage() { + @ApiModelProperty( + value = "The identifier of the Controller Service." + ) + public String getId() { + return id; } - @Override - public MessageType getType() { - return MessageType.GET_GROUP_FOR_USER; + public void setId(String id) { + this.id = id; } - public String getDn() { - return dn; + @ApiModelProperty( + value = "The new state of the references for the controller service.", + allowableValues = "ENABLED, DISABLED, RUNNING, STOPPED" + ) + public String getState() { + return state; } - public void setDn(String dn) { - this.dn = dn; + public void setState(String state) { + this.state = state; } - - public String getResponse() { - return response; - } - - public void setResponse(String response) { - this.response = response; - } - } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/.gitignore b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/.gitignore deleted file mode 100755 index ea8c4bf7f3..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/pom.xml b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/pom.xml deleted file mode 100644 index 2f0147be89..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - 4.0.0 - - org.apache.nifi - nifi-framework - 1.0.0-SNAPSHOT - - nifi-cluster-authorization-provider - - - org.apache.nifi - nifi-api - - - org.apache.nifi - nifi-file-authorization-provider - - - org.apache.nifi - nifi-framework-cluster-protocol - - - org.apache.nifi - nifi-framework-cluster - - - org.apache.nifi - nifi-socket-utils - - - diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/ClusterManagerAuthorizationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/ClusterManagerAuthorizationProvider.java deleted file mode 100644 index 2b3b38c4c3..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/ClusterManagerAuthorizationProvider.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.cluster.authorization; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.AuthorityProviderConfigurationContext; -import org.apache.nifi.authorization.AuthorityProviderInitializationContext; -import org.apache.nifi.authorization.FileAuthorizationProvider; -import org.apache.nifi.authorization.annotation.AuthorityProviderContext; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.authorization.exception.ProviderDestructionException; -import org.apache.nifi.cluster.authorization.protocol.message.DoesDnExistMessage; -import org.apache.nifi.cluster.authorization.protocol.message.GetAuthoritiesMessage; -import org.apache.nifi.cluster.authorization.protocol.message.GetGroupForUserMessage; -import org.apache.nifi.cluster.authorization.protocol.message.ProtocolMessage; -import static org.apache.nifi.cluster.authorization.protocol.message.ProtocolMessage.MessageType.DOES_DN_EXIST; -import static org.apache.nifi.cluster.authorization.protocol.message.ProtocolMessage.MessageType.GET_AUTHORITIES; -import static org.apache.nifi.cluster.authorization.protocol.message.ProtocolMessage.MessageType.GET_GROUP_FOR_USER; -import org.apache.nifi.cluster.authorization.protocol.message.jaxb.JaxbProtocolUtils; -import org.apache.nifi.cluster.manager.impl.WebClusterManager; -import org.apache.nifi.cluster.protocol.ProtocolContext; -import org.apache.nifi.cluster.protocol.ProtocolMessageMarshaller; -import org.apache.nifi.cluster.protocol.ProtocolMessageUnmarshaller; -import org.apache.nifi.cluster.protocol.jaxb.JaxbProtocolContext; -import org.apache.nifi.io.socket.ServerSocketConfiguration; -import org.apache.nifi.io.socket.SocketListener; -import org.apache.nifi.io.socket.SocketUtils; -import org.apache.nifi.io.socket.multicast.DiscoverableService; -import org.apache.nifi.io.socket.multicast.DiscoverableServiceImpl; -import org.apache.nifi.logging.NiFiLog; -import org.apache.nifi.util.NiFiProperties; -import static org.apache.nifi.util.NiFiProperties.CLUSTER_MANAGER_ADDRESS; -import org.apache.nifi.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -/** - * Provides authorities for the NCM in clustered environments. Communication - * occurs over TCP/IP sockets. All method calls are deferred to the - * FileAuthorizationProvider. - */ -public class ClusterManagerAuthorizationProvider extends FileAuthorizationProvider implements AuthorityProvider, ApplicationContextAware { - - public static final String AUTHORITY_PROVIDER_SERVIVE_NAME = "cluster-authority-provider"; - - private static final Logger logger = new NiFiLog(LoggerFactory.getLogger(ClusterManagerAuthorizationProvider.class)); - private static final String CLUSTER_MANAGER_AUTHORITY_PROVIDER_PORT = "Authority Provider Port"; - private static final String CLUSTER_MANAGER_AUTHORITY_PROVIDER_THREADS = "Authority Provider Threads"; - private static final int DEFAULT_CLUSTER_MANAGER_AUTHORITY_PROVIDER_THREADS = 10; - - private WebClusterManager clusterManager; - private ProtocolContext authorityProviderProtocolContext; - private SocketListener socketListener; - private NiFiProperties properties; - private ApplicationContext applicationContext; - - @Override - public void initialize(final AuthorityProviderInitializationContext initializationContext) throws ProviderCreationException { - super.initialize(initializationContext); - } - - @Override - public void onConfigured(final AuthorityProviderConfigurationContext configurationContext) throws ProviderCreationException { - super.onConfigured(configurationContext); - - // get the socket address of the cluster authority provider - final InetSocketAddress clusterAuthorityProviderAddress = getClusterManagerAuthorityProviderAddress(configurationContext); - - // get the cluster manager - clusterManager = applicationContext.getBean("clusterManager", WebClusterManager.class); - - // if using multicast, then the authority provider's service is broadcasted - if (properties.getClusterProtocolUseMulticast()) { - - // create the authority provider service for discovery - final DiscoverableService clusterAuthorityProviderService = new DiscoverableServiceImpl(AUTHORITY_PROVIDER_SERVIVE_NAME, clusterAuthorityProviderAddress); - - // register the authority provider service with the cluster manager - clusterManager.addBroadcastedService(clusterAuthorityProviderService); - } - - // get the number of protocol listening thread - final int numThreads = getClusterManagerAuthorityProviderThreads(configurationContext); - - // the server socket configuration - final ServerSocketConfiguration configuration = applicationContext.getBean("protocolServerSocketConfiguration", ServerSocketConfiguration.class); - - // the authority provider listens for node messages - socketListener = new SocketListener(numThreads, clusterAuthorityProviderAddress.getPort(), configuration) { - @Override - public void dispatchRequest(final Socket socket) { - ClusterManagerAuthorizationProvider.this.dispatchRequest(socket); - } - }; - - // start the socket listener - if (socketListener != null && !socketListener.isRunning()) { - try { - socketListener.start(); - } catch (final IOException ioe) { - throw new ProviderCreationException("Failed to start Cluster Manager Authorization Provider due to: " + ioe, ioe); - } - } - - // initialize the protocol context - authorityProviderProtocolContext = new JaxbProtocolContext(JaxbProtocolUtils.JAXB_CONTEXT); - } - - @Override - public void preDestruction() throws ProviderDestructionException { - if (socketListener != null && socketListener.isRunning()) { - try { - socketListener.stop(); - } catch (final IOException ioe) { - throw new ProviderDestructionException("Failed to stop Cluster Manager Authorization Provider due to: " + ioe, ioe); - } - } - super.preDestruction(); - } - - private int getClusterManagerAuthorityProviderThreads(final AuthorityProviderConfigurationContext configurationContext) { - try { - return Integer.parseInt(configurationContext.getProperty(CLUSTER_MANAGER_AUTHORITY_PROVIDER_THREADS)); - } catch (NumberFormatException nfe) { - return DEFAULT_CLUSTER_MANAGER_AUTHORITY_PROVIDER_THREADS; - } - } - - private InetSocketAddress getClusterManagerAuthorityProviderAddress(final AuthorityProviderConfigurationContext configurationContext) { - try { - String socketAddress = properties.getProperty(CLUSTER_MANAGER_ADDRESS); - if (StringUtils.isBlank(socketAddress)) { - socketAddress = "localhost"; - } - return InetSocketAddress.createUnresolved(socketAddress, getClusterManagerAuthorityProviderPort(configurationContext)); - } catch (Exception ex) { - throw new RuntimeException("Invalid manager authority provider address/port due to: " + ex, ex); - } - } - - private Integer getClusterManagerAuthorityProviderPort(final AuthorityProviderConfigurationContext configurationContext) { - final String authorityProviderPort = configurationContext.getProperty(CLUSTER_MANAGER_AUTHORITY_PROVIDER_PORT); - if (authorityProviderPort == null || authorityProviderPort.trim().isEmpty()) { - throw new ProviderCreationException("The authority provider port must be specified."); - } - - return Integer.parseInt(authorityProviderPort); - } - - private void dispatchRequest(final Socket socket) { - try { - // unmarshall message - final ProtocolMessageUnmarshaller unmarshaller = authorityProviderProtocolContext.createUnmarshaller(); - final ProtocolMessage request = unmarshaller.unmarshal(socket.getInputStream()); - final ProtocolMessage response = request; - - try { - switch (request.getType()) { - case DOES_DN_EXIST: { - final DoesDnExistMessage castedMsg = (DoesDnExistMessage) request; - castedMsg.setResponse(doesDnExist(castedMsg.getDn())); - break; - } - case GET_AUTHORITIES: { - final GetAuthoritiesMessage castedMsg = (GetAuthoritiesMessage) request; - castedMsg.setResponse(getAuthorities(castedMsg.getDn())); - break; - } - case GET_GROUP_FOR_USER: { - final GetGroupForUserMessage castedMsg = (GetGroupForUserMessage) request; - castedMsg.setResponse(getGroupForUser(castedMsg.getDn())); - break; - } - default: { - throw new Exception("Unsupported Message Type: " + request.getType()); - } - } - } catch (final Exception ex) { - response.setExceptionClass(ex.getClass().getName()); - response.setExceptionMessage(ex.getMessage()); - } - - final ProtocolMessageMarshaller marshaller = authorityProviderProtocolContext.createMarshaller(); - marshaller.marshal(response, socket.getOutputStream()); - - } catch (final Exception e) { - logger.warn("Failed processing Socket Authorization Provider protocol message due to " + e, e); - } finally { - SocketUtils.closeQuietly(socket); - } - } - - @Override - @AuthorityProviderContext - public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - @Override - @AuthorityProviderContext - public void setNiFiProperties(NiFiProperties properties) { - super.setNiFiProperties(properties); - this.properties = properties; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/NodeAuthorizationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/NodeAuthorizationProvider.java deleted file mode 100644 index 840422ff54..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/NodeAuthorizationProvider.java +++ /dev/null @@ -1,389 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.cluster.authorization; - -import org.apache.nifi.cluster.authorization.protocol.message.DoesDnExistMessage; -import org.apache.nifi.cluster.authorization.protocol.message.GetAuthoritiesMessage; -import org.apache.nifi.cluster.authorization.protocol.message.ProtocolMessage; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.AuthorityProviderConfigurationContext; -import org.apache.nifi.authorization.AuthorityProviderInitializationContext; -import org.apache.nifi.authorization.DownloadAuthorization; -import org.apache.nifi.authorization.annotation.AuthorityProviderContext; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.IdentityAlreadyExistsException; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.authorization.exception.ProviderDestructionException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.cluster.authorization.protocol.message.GetGroupForUserMessage; -import org.apache.nifi.cluster.authorization.protocol.message.jaxb.JaxbProtocolUtils; -import org.apache.nifi.io.socket.SocketConfiguration; -import org.apache.nifi.io.socket.SocketUtils; -import org.apache.nifi.io.socket.multicast.DiscoverableService; -import org.apache.nifi.cluster.protocol.ProtocolContext; -import org.apache.nifi.cluster.protocol.ProtocolMessageMarshaller; -import org.apache.nifi.cluster.protocol.ProtocolMessageUnmarshaller; -import org.apache.nifi.cluster.protocol.impl.ClusterServiceDiscovery; -import org.apache.nifi.cluster.protocol.impl.ClusterServiceLocator; -import org.apache.nifi.cluster.protocol.jaxb.JaxbProtocolContext; -import org.apache.nifi.io.socket.multicast.DiscoverableServiceImpl; -import org.apache.nifi.io.socket.multicast.MulticastConfiguration; -import org.apache.nifi.logging.NiFiLog; -import org.apache.nifi.util.NiFiProperties; -import static org.apache.nifi.util.NiFiProperties.CLUSTER_NODE_UNICAST_MANAGER_ADDRESS; -import org.apache.nifi.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - -/** - * Provides authorities for nodes in clustered environments. Communication - * occurs over TCP/IP sockets. All method calls are communicated to the cluster - * manager provider via socket. - */ -public class NodeAuthorizationProvider implements AuthorityProvider, ApplicationContextAware { - - private static final Logger logger = new NiFiLog(LoggerFactory.getLogger(NodeAuthorizationProvider.class)); - private static final String CLUSTER_NODE_MANAGER_AUTHORITY_PROVIDER_PORT = "Cluster Manager Authority Provider Port"; - - private ProtocolContext authorityProviderProtocolContext; - private SocketConfiguration socketConfiguration; - private ClusterServiceLocator serviceLocator; - private ApplicationContext applicationContext; - private NiFiProperties properties; - - @Override - public void initialize(AuthorityProviderInitializationContext initializationContext) throws ProviderCreationException { - } - - @Override - public void onConfigured(final AuthorityProviderConfigurationContext configurationContext) throws ProviderCreationException { - // TODO clear user cache? - - // if using multicast, then the authority provider's service is broadcasted - if (properties.getClusterProtocolUseMulticast()) { - // create the service discovery - final ClusterServiceDiscovery serviceDiscovery = new ClusterServiceDiscovery( - ClusterManagerAuthorizationProvider.AUTHORITY_PROVIDER_SERVIVE_NAME, - properties.getClusterProtocolMulticastAddress(), - applicationContext.getBean("protocolMulticastConfiguration", MulticastConfiguration.class), - applicationContext.getBean("protocolContext", ProtocolContext.class)); - - // create service location configuration - final ClusterServiceLocator.AttemptsConfig config = new ClusterServiceLocator.AttemptsConfig(); - config.setNumAttempts(3); - config.setTimeBetweenAttempts(1); - config.setTimeBetweenAttempsUnit(TimeUnit.SECONDS); - - serviceLocator = new ClusterServiceLocator(serviceDiscovery); - serviceLocator.setAttemptsConfig(config); - } else { - final InetSocketAddress serviceAddress = getClusterNodeManagerAuthorityProviderAddress(configurationContext); - final DiscoverableService service = new DiscoverableServiceImpl(ClusterManagerAuthorizationProvider.AUTHORITY_PROVIDER_SERVIVE_NAME, serviceAddress); - serviceLocator = new ClusterServiceLocator(service); - } - - try { - // start the service locator - serviceLocator.start(); - } catch (final IOException ioe) { - throw new ProviderCreationException(ioe); - } - - // the socket configuration - socketConfiguration = applicationContext.getBean("protocolSocketConfiguration", SocketConfiguration.class); - - // initialize the protocol context - authorityProviderProtocolContext = new JaxbProtocolContext(JaxbProtocolUtils.JAXB_CONTEXT); - } - - private InetSocketAddress getClusterNodeManagerAuthorityProviderAddress(final AuthorityProviderConfigurationContext configurationContext) { - try { - String socketAddress = properties.getProperty(CLUSTER_NODE_UNICAST_MANAGER_ADDRESS); - if (StringUtils.isBlank(socketAddress)) { - socketAddress = "localhost"; - } - return InetSocketAddress.createUnresolved(socketAddress, getClusterNodeManagerAuthorityProviderPort(configurationContext)); - } catch (Exception ex) { - throw new ProviderCreationException("Invalid cluster manager authority provider address/port due to: " + ex, ex); - } - } - - private Integer getClusterNodeManagerAuthorityProviderPort(final AuthorityProviderConfigurationContext configurationContext) { - final String nodeAuthorityProviderPort = configurationContext.getProperty(CLUSTER_NODE_MANAGER_AUTHORITY_PROVIDER_PORT); - if (nodeAuthorityProviderPort == null || nodeAuthorityProviderPort.trim().isEmpty()) { - throw new ProviderCreationException("The cluster manager authority provider port must be specified."); - } - - return Integer.parseInt(nodeAuthorityProviderPort); - } - - @Override - public void setAuthorities(String dn, Set authorities) throws AuthorityAccessException { - throw new AuthorityAccessException("Nodes are not allowed to set user authorities."); - } - - @Override - public void addUser(String dn, String group) throws IdentityAlreadyExistsException, AuthorityAccessException { - throw new AuthorityAccessException("Nodes are not allowed to add users."); - } - - @Override - public boolean doesDnExist(String dn) throws AuthorityAccessException { - // create message - final DoesDnExistMessage msg = new DoesDnExistMessage(); - msg.setDn(dn); - - Socket socket = null; - try { - - final InetSocketAddress socketAddress = getServiceAddress(); - if (socketAddress == null) { - throw new AuthorityAccessException("Cluster Authority Provider's address is not known."); - } - - try { - // create a socket - socket = SocketUtils.createSocket(socketAddress, socketConfiguration); - } catch (final IOException ioe) { - throw new AuthorityAccessException("Failed to create socket due to: " + ioe, ioe); - } - - try { - // marshal message to output stream - final ProtocolMessageMarshaller marshaller = authorityProviderProtocolContext.createMarshaller(); - marshaller.marshal(msg, socket.getOutputStream()); - } catch (final IOException ioe) { - throw new AuthorityAccessException("Failed marshalling '" + msg.getType() + "' protocol message due to: " + ioe, ioe); - } - - try { - - // unmarshall response and return - final ProtocolMessageUnmarshaller unmarshaller = authorityProviderProtocolContext.createUnmarshaller(); - final DoesDnExistMessage response = (DoesDnExistMessage) unmarshaller.unmarshal(socket.getInputStream()); - - // check if there was an exception - if (response.wasException()) { - throw new AuthorityAccessException(response.getExceptionMessage()); - } - - // return provider's response - return response.getResponse(); - - } catch (final IOException ioe) { - throw new AuthorityAccessException("Failed unmarshalling '" + msg.getType() + "' response protocol message due to: " + ioe, ioe); - } - - } finally { - SocketUtils.closeQuietly(socket); - } - } - - @Override - public Set getAuthorities(String dn) throws UnknownIdentityException, AuthorityAccessException { - // create message - final GetAuthoritiesMessage msg = new GetAuthoritiesMessage(); - msg.setDn(dn); - - Socket socket = null; - try { - - final InetSocketAddress socketAddress = getServiceAddress(); - if (socketAddress == null) { - throw new AuthorityAccessException("Cluster Authority Provider's address is not known."); - } - - try { - // create a socket - socket = SocketUtils.createSocket(socketAddress, socketConfiguration); - } catch (final IOException ioe) { - throw new AuthorityAccessException("Failed to create socket due to: " + ioe, ioe); - } - - try { - // marshal message to output stream - final ProtocolMessageMarshaller marshaller = authorityProviderProtocolContext.createMarshaller(); - marshaller.marshal(msg, socket.getOutputStream()); - } catch (final IOException ioe) { - throw new AuthorityAccessException("Failed marshalling '" + msg.getType() + "' protocol message due to: " + ioe, ioe); - } - - try { - - // unmarshall response and return - final ProtocolMessageUnmarshaller unmarshaller = authorityProviderProtocolContext.createUnmarshaller(); - final GetAuthoritiesMessage response = (GetAuthoritiesMessage) unmarshaller.unmarshal(socket.getInputStream()); - - // check if there was an exception - if (response.wasException()) { - if (isException(UnknownIdentityException.class, response)) { - throw new UnknownIdentityException(response.getExceptionMessage()); - } else { - throw new AuthorityAccessException(response.getExceptionMessage()); - } - } - - // return provider's response - return response.getResponse(); - - } catch (final IOException ioe) { - throw new AuthorityAccessException("Failed unmarshalling '" + msg.getType() + "' response protocol message due to: " + ioe, ioe); - } - - } finally { - SocketUtils.closeQuietly(socket); - } - } - - @Override - public Set getUsers(Authority authority) throws AuthorityAccessException { - throw new AuthorityAccessException("Nodes are not allowed to get users for a given authority."); - } - - @Override - public void revokeUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - throw new AuthorityAccessException("Nodes are not allowed to revoke users."); - } - - @Override - public void setUsersGroup(Set dns, String group) throws UnknownIdentityException, AuthorityAccessException { - throw new AuthorityAccessException("Nodes are not allowed to set user groups."); - } - - @Override - public void ungroupUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - throw new AuthorityAccessException("Nodes are not allowed to ungroup users."); - } - - @Override - public void ungroup(String group) throws AuthorityAccessException { - throw new AuthorityAccessException("Nodes are not allowed to ungroup."); - } - - @Override - public DownloadAuthorization authorizeDownload(List dnChain, Map attributes) throws UnknownIdentityException, AuthorityAccessException { - return DownloadAuthorization.approved(); - } - - @Override - public String getGroupForUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - // create message - final GetGroupForUserMessage msg = new GetGroupForUserMessage(); - msg.setDn(dn); - - Socket socket = null; - try { - - final InetSocketAddress socketAddress = getServiceAddress(); - if (socketAddress == null) { - throw new AuthorityAccessException("Cluster Authority Provider's address is not known."); - } - - try { - // create a socket - socket = SocketUtils.createSocket(socketAddress, socketConfiguration); - } catch (final IOException ioe) { - throw new AuthorityAccessException("Failed to create socket due to: " + ioe, ioe); - } - - try { - // marshal message to output stream - final ProtocolMessageMarshaller marshaller = authorityProviderProtocolContext.createMarshaller(); - marshaller.marshal(msg, socket.getOutputStream()); - } catch (final IOException ioe) { - throw new AuthorityAccessException("Failed marshalling '" + msg.getType() + "' protocol message due to: " + ioe, ioe); - } - - try { - - // unmarshall response and return - final ProtocolMessageUnmarshaller unmarshaller = authorityProviderProtocolContext.createUnmarshaller(); - final GetGroupForUserMessage response = (GetGroupForUserMessage) unmarshaller.unmarshal(socket.getInputStream()); - - // check if there was an exception - if (response.wasException()) { - if (isException(UnknownIdentityException.class, response)) { - throw new UnknownIdentityException(response.getExceptionMessage()); - } else { - throw new AuthorityAccessException(response.getExceptionMessage()); - } - } - - return response.getResponse(); - } catch (final IOException ioe) { - throw new AuthorityAccessException("Failed unmarshalling '" + msg.getType() + "' response protocol message due to: " + ioe, ioe); - } - - } finally { - SocketUtils.closeQuietly(socket); - } - } - - @Override - public void revokeGroup(String group) throws UnknownIdentityException, AuthorityAccessException { - throw new AuthorityAccessException("Nodes are not allowed to revoke groups."); - } - - @Override - public void preDestruction() throws ProviderDestructionException { - try { - if (serviceLocator != null && serviceLocator.isRunning()) { - serviceLocator.stop(); - } - } catch (final IOException ioe) { - throw new ProviderDestructionException(ioe); - } - } - - @Override - @AuthorityProviderContext - public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - @AuthorityProviderContext - public void setNiFiProperties(NiFiProperties properties) { - this.properties = properties; - } - - private InetSocketAddress getServiceAddress() { - final DiscoverableService service = serviceLocator.getService(); - if (service != null) { - return service.getServiceAddress(); - } - return null; - } - - private boolean isException(final Class exception, final ProtocolMessage protocolMessage) { - if (protocolMessage.wasException()) { - return exception.getName().equals(protocolMessage.getExceptionClass()); - } else { - return false; - } - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/DoesDnExistMessage.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/DoesDnExistMessage.java deleted file mode 100644 index 54361406f2..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/DoesDnExistMessage.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.cluster.authorization.protocol.message; - -import javax.xml.bind.annotation.XmlRootElement; -import org.apache.nifi.cluster.authorization.protocol.message.ProtocolMessage.MessageType; - -/** - */ -@XmlRootElement(name = "doesDnExistMessage") -public class DoesDnExistMessage extends ProtocolMessage { - - private String dn; - - private boolean response; - - public DoesDnExistMessage() { - } - - @Override - public MessageType getType() { - return MessageType.DOES_DN_EXIST; - } - - public String getDn() { - return dn; - } - - public void setDn(String dn) { - this.dn = dn; - } - - public boolean getResponse() { - return response; - } - - public void setResponse(boolean response) { - this.response = response; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/GetAuthoritiesMessage.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/GetAuthoritiesMessage.java deleted file mode 100644 index 50d371d0ac..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/GetAuthoritiesMessage.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.cluster.authorization.protocol.message; - -import java.util.HashSet; -import java.util.Set; -import javax.xml.bind.annotation.XmlRootElement; -import org.apache.nifi.authorization.Authority; - -/** - */ -@XmlRootElement(name = "getAuthoritiesMessage") -public class GetAuthoritiesMessage extends ProtocolMessage { - - private String dn; - - private Set response = new HashSet<>(); - - public GetAuthoritiesMessage() { - } - - @Override - public MessageType getType() { - return MessageType.GET_AUTHORITIES; - } - - public String getDn() { - return dn; - } - - public void setDn(String dn) { - this.dn = dn; - } - - public Set getResponse() { - return response; - } - - public void setResponse(Set response) { - this.response = response; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/ProtocolMessage.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/ProtocolMessage.java deleted file mode 100644 index ddeb69e2c0..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/ProtocolMessage.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.cluster.authorization.protocol.message; - -/** - */ -public abstract class ProtocolMessage { - - private String exceptionClass; - private String exceptionMessage; - - public static enum MessageType { - - DOES_DN_EXIST, - GET_AUTHORITIES, - GET_USERS, - GET_GROUP_FOR_USER - } - - public abstract MessageType getType(); - - public boolean wasException() { - return exceptionClass != null; - } - - public String getExceptionMessage() { - return exceptionMessage; - } - - public void setExceptionMessage(final String exceptionMessage) { - this.exceptionMessage = exceptionMessage; - } - - public String getExceptionClass() { - return exceptionClass; - } - - public void setExceptionClass(String exceptionClass) { - this.exceptionClass = exceptionClass; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/jaxb/JaxbProtocolUtils.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/jaxb/JaxbProtocolUtils.java deleted file mode 100644 index 2a32d849d9..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/jaxb/JaxbProtocolUtils.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.cluster.authorization.protocol.message.jaxb; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; - -/** - */ -public final class JaxbProtocolUtils { - - public static final String JAXB_CONTEXT_PATH = ObjectFactory.class.getPackage().getName(); - - public static final JAXBContext JAXB_CONTEXT = initializeJaxbContext(); - - /** - * Load the JAXBContext version. - */ - private static JAXBContext initializeJaxbContext() { - try { - return JAXBContext.newInstance(JAXB_CONTEXT_PATH); - } catch (JAXBException e) { - throw new RuntimeException("Unable to create JAXBContext."); - } - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/jaxb/ObjectFactory.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/jaxb/ObjectFactory.java deleted file mode 100644 index 2e70a1937f..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/java/org/apache/nifi/cluster/authorization/protocol/message/jaxb/ObjectFactory.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.cluster.authorization.protocol.message.jaxb; - -import javax.xml.bind.annotation.XmlRegistry; -import org.apache.nifi.cluster.authorization.protocol.message.DoesDnExistMessage; -import org.apache.nifi.cluster.authorization.protocol.message.GetAuthoritiesMessage; -import org.apache.nifi.cluster.authorization.protocol.message.GetGroupForUserMessage; - -/** - */ -@XmlRegistry -public class ObjectFactory { - - public ObjectFactory() { - } - - public DoesDnExistMessage createDoesDnExistMessage() { - return new DoesDnExistMessage(); - } - - public GetAuthoritiesMessage createGetAuthoritiesMessage() { - return new GetAuthoritiesMessage(); - } - - public GetGroupForUserMessage createGetGroupForUserMessage() { - return new GetGroupForUserMessage(); - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider deleted file mode 100644 index 56f4c3e32f..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-cluster-authorization-provider/src/main/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider +++ /dev/null @@ -1,16 +0,0 @@ -# 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. -org.apache.nifi.cluster.authorization.ClusterManagerAuthorizationProvider -org.apache.nifi.cluster.authorization.NodeAuthorizationProvider \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-documentation/src/test/resources/conf/nifi.properties b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-documentation/src/test/resources/conf/nifi.properties index bfc93762cf..c6b5d36295 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-documentation/src/test/resources/conf/nifi.properties +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-documentation/src/test/resources/conf/nifi.properties @@ -84,11 +84,7 @@ nifi.security.truststore= nifi.security.truststoreType= nifi.security.truststorePasswd= nifi.security.needClientAuth= -nifi.security.authorizedUsers.file=./target/conf/authorized-users.xml -nifi.security.user.credential.cache.duration=24 hours -nifi.security.user.authority.provider=nifi.authorization.FileAuthorizationProvider -nifi.security.support.new.account.requests= -nifi.security.default.user.roles= +nifi.security.user.authorizer= # cluster common properties (cluster manager and nodes must have same values) # nifi.cluster.protocol.heartbeat.interval=5 sec diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/pom.xml b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/pom.xml deleted file mode 100644 index caa75de6e6..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - 4.0.0 - - org.apache.nifi - nifi-framework - 1.0.0-SNAPSHOT - - nifi-file-authorization-provider - - - - src/main/resources - - - src/main/xsd - - - - - org.codehaus.mojo - jaxb2-maven-plugin - - - xjc - - xjc - - - org.apache.nifi.user.generated - - - - - ${project.build.directory}/generated-sources/jaxb - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - **/user/generated/*.java - - - - - - - - org.apache.nifi - nifi-api - - - org.apache.nifi - nifi-utils - - - org.apache.nifi - nifi-properties - - - org.apache.commons - commons-lang3 - - - commons-codec - commons-codec - test - - - diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/java/org/apache/nifi/authorization/FileAuthorizationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/java/org/apache/nifi/authorization/FileAuthorizationProvider.java deleted file mode 100644 index 9c2cad5fdb..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/java/org/apache/nifi/authorization/FileAuthorizationProvider.java +++ /dev/null @@ -1,496 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import org.apache.nifi.authorization.annotation.AuthorityProviderContext; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.IdentityAlreadyExistsException; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.nifi.util.file.FileUtils; -import org.apache.nifi.user.generated.ObjectFactory; -import org.apache.nifi.user.generated.Role; -import org.apache.nifi.user.generated.User; -import org.apache.nifi.user.generated.Users; -import org.apache.nifi.util.NiFiProperties; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.xml.sax.SAXException; - -/** - * Provides identity checks and grants authorities. - */ -public class FileAuthorizationProvider implements AuthorityProvider { - - private static final Logger logger = LoggerFactory.getLogger(FileAuthorizationProvider.class); - private static final String USERS_XSD = "/users.xsd"; - private static final String JAXB_GENERATED_PATH = "org.apache.nifi.user.generated"; - private static final JAXBContext JAXB_CONTEXT = initializeJaxbContext(); - - /** - * Load the JAXBContext. - */ - private static JAXBContext initializeJaxbContext() { - try { - return JAXBContext.newInstance(JAXB_GENERATED_PATH, FileAuthorizationProvider.class.getClassLoader()); - } catch (JAXBException e) { - throw new RuntimeException("Unable to create JAXBContext."); - } - } - - private NiFiProperties properties; - private File usersFile; - private File restoreUsersFile; - private Users users; - private final Set defaultAuthorities = new HashSet<>(); - - @Override - public void initialize(final AuthorityProviderInitializationContext initializationContext) throws ProviderCreationException { - } - - @Override - public void onConfigured(final AuthorityProviderConfigurationContext configurationContext) throws ProviderCreationException { - try { - final String usersFilePath = configurationContext.getProperty("Authorized Users File"); - if (usersFilePath == null || usersFilePath.trim().isEmpty()) { - throw new ProviderCreationException("The authorized users file must be specified."); - } - - // the users file instance will never be null because a default is used - usersFile = new File(usersFilePath); - final File usersFileDirectory = usersFile.getParentFile(); - - // the restore directory is optional and may be null - final File restoreDirectory = properties.getRestoreDirectory(); - - if (restoreDirectory != null) { - - // sanity check that restore directory is a directory, creating it if necessary - FileUtils.ensureDirectoryExistAndCanAccess(restoreDirectory); - - // check that restore directory is not the same as the primary directory - if (usersFileDirectory.getAbsolutePath().equals(restoreDirectory.getAbsolutePath())) { - throw new ProviderCreationException(String.format("Authorized User's directory '%s' is the same as restore directory '%s' ", - usersFileDirectory.getAbsolutePath(), restoreDirectory.getAbsolutePath())); - } - - // the restore copy will have same file name, but reside in a different directory - restoreUsersFile = new File(restoreDirectory, usersFile.getName()); - - // sync the primary copy with the restore copy - try { - FileUtils.syncWithRestore(usersFile, restoreUsersFile, logger); - } catch (final IOException | IllegalStateException ioe) { - throw new ProviderCreationException(ioe); - } - - } - - // load the users from the specified file - if (usersFile.exists()) { - // find the schema - final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - final Schema schema = schemaFactory.newSchema(FileAuthorizationProvider.class.getResource(USERS_XSD)); - - // attempt to unmarshal - final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); - unmarshaller.setSchema(schema); - final JAXBElement element = unmarshaller.unmarshal(new StreamSource(usersFile), Users.class); - users = element.getValue(); - } else { - final ObjectFactory objFactory = new ObjectFactory(); - users = objFactory.createUsers(); - } - - // attempt to load a default roles - final String rawDefaultAuthorities = configurationContext.getProperty("Default User Roles"); - if (StringUtils.isNotBlank(rawDefaultAuthorities)) { - final Set invalidDefaultAuthorities = new HashSet<>(); - - // validate the specified authorities - final String[] rawDefaultAuthorityList = rawDefaultAuthorities.split(","); - for (String rawAuthority : rawDefaultAuthorityList) { - rawAuthority = rawAuthority.trim(); - final Authority authority = Authority.valueOfAuthority(rawAuthority); - if (authority == null) { - invalidDefaultAuthorities.add(rawAuthority); - } else { - defaultAuthorities.add(rawAuthority); - } - } - - // report any unrecognized authorities - if (!invalidDefaultAuthorities.isEmpty()) { - logger.warn(String.format("The following default role(s) '%s' were not recognized. Possible values: %s.", - StringUtils.join(invalidDefaultAuthorities, ", "), StringUtils.join(Authority.getRawAuthorities(), ", "))); - } - } - } catch (IOException | ProviderCreationException | SAXException | JAXBException e) { - throw new ProviderCreationException(e); - } - - } - - @Override - public void preDestruction() { - } - - private boolean hasDefaultRoles() { - return !defaultAuthorities.isEmpty(); - } - - @Override - public boolean doesDnExist(String dn) throws AuthorityAccessException { - if (hasDefaultRoles()) { - return true; - } - - final User user = getUser(dn); - return user != null; - } - - @Override - public synchronized Set getAuthorities(String dn) throws UnknownIdentityException, AuthorityAccessException { - final Set authorities = EnumSet.noneOf(Authority.class); - - // get the user - final User user = getUser(dn); - - // ensure the user was located - if (user == null) { - if (hasDefaultRoles()) { - logger.debug(String.format("User DN not found: %s. Creating new user with default roles.", dn)); - - // create the user (which will automatically add any default authorities) - addUser(dn, null); - - // get the authorities for the newly created user - authorities.addAll(getAuthorities(dn)); - } else { - throw new UnknownIdentityException(String.format("User DN not found: %s.", dn)); - } - } else { - // create the authorities that this user has - for (final Role role : user.getRole()) { - authorities.add(Authority.valueOfAuthority(role.getName())); - } - } - - return authorities; - } - - @Override - public synchronized void setAuthorities(String dn, Set authorities) throws UnknownIdentityException, AuthorityAccessException { - // get the user - final User user = getUser(dn); - - // ensure the user was located - if (user == null) { - throw new UnknownIdentityException(String.format("User DN not found: %s.", dn)); - } - - // add the user authorities - setUserAuthorities(user, authorities); - - try { - // save the file - save(); - } catch (Exception e) { - throw new AuthorityAccessException(e.getMessage(), e); - } - } - - private void setUserAuthorities(final User user, final Set authorities) { - // clear the existing rules - user.getRole().clear(); - - // set the new roles - final ObjectFactory objFactory = new ObjectFactory(); - for (final Authority authority : authorities) { - final Role role = objFactory.createRole(); - role.setName(authority.toString()); - - // add the new role - user.getRole().add(role); - } - } - - @Override - public synchronized void addUser(String dn, String group) throws IdentityAlreadyExistsException, AuthorityAccessException { - final User user = getUser(dn); - - // ensure the user doesn't already exist - if (user != null) { - throw new IdentityAlreadyExistsException(String.format("User DN already exists: %s", dn)); - } - - // create the new user - final ObjectFactory objFactory = new ObjectFactory(); - final User newUser = objFactory.createUser(); - - // set the user properties - newUser.setDn(dn); - newUser.setGroup(group); - - // add default roles if appropriate - if (hasDefaultRoles()) { - for (final String authority : defaultAuthorities) { - Role role = objFactory.createRole(); - role.setName(authority); - - // add the role - newUser.getRole().add(role); - } - } - - // add the user - users.getUser().add(newUser); - - try { - // save the file - save(); - } catch (Exception e) { - throw new AuthorityAccessException(e.getMessage(), e); - } - } - - @Override - public synchronized Set getUsers(Authority authority) throws AuthorityAccessException { - final Set userSet = new HashSet<>(); - for (final User user : users.getUser()) { - for (final Role role : user.getRole()) { - if (role.getName().equals(authority.toString())) { - userSet.add(user.getDn()); - } - } - } - return userSet; - } - - @Override - public synchronized void revokeUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - // get the user - final User user = getUser(dn); - - // ensure the user was located - if (user == null) { - throw new UnknownIdentityException(String.format("User DN not found: %s.", dn)); - } - - // remove the specified user - users.getUser().remove(user); - - try { - // save the file - save(); - } catch (Exception e) { - throw new AuthorityAccessException(e.getMessage(), e); - } - } - - @Override - public void setUsersGroup(Set dns, String group) throws UnknownIdentityException, AuthorityAccessException { - final Collection groupedUsers = new HashSet<>(); - - // get the specified users - for (final String dn : dns) { - // get the user - final User user = getUser(dn); - - // ensure the user was located - if (user == null) { - throw new UnknownIdentityException(String.format("User DN not found: %s.", dn)); - } - - groupedUsers.add(user); - } - - // update each user group - for (final User user : groupedUsers) { - user.setGroup(group); - } - - try { - // save the file - save(); - } catch (Exception e) { - throw new AuthorityAccessException(e.getMessage(), e); - } - } - - @Override - public void ungroupUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - // get the user - final User user = getUser(dn); - - // ensure the user was located - if (user == null) { - throw new UnknownIdentityException(String.format("User DN not found: %s.", dn)); - } - - // remove the users group - user.setGroup(null); - - try { - // save the file - save(); - } catch (Exception e) { - throw new AuthorityAccessException(e.getMessage(), e); - } - } - - @Override - public void ungroup(String group) throws AuthorityAccessException { - // get the user group - final Collection userGroup = getUserGroup(group); - - // ensure the user group was located - if (userGroup == null) { - return; - } - - // update each user group - for (final User user : userGroup) { - user.setGroup(null); - } - - try { - // save the file - save(); - } catch (Exception e) { - throw new AuthorityAccessException(e.getMessage(), e); - } - } - - @Override - public String getGroupForUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - // get the user - final User user = getUser(dn); - - // ensure the user was located - if (user == null) { - throw new UnknownIdentityException(String.format("User DN not found: %s.", dn)); - } - - return user.getGroup(); - } - - @Override - public void revokeGroup(String group) throws UnknownIdentityException, AuthorityAccessException { - // get the user group - final Collection userGroup = getUserGroup(group); - - // ensure the user group was located - if (userGroup == null) { - throw new UnknownIdentityException(String.format("User group not found: %s.", group)); - } - - // remove each user in the group - for (final User user : userGroup) { - users.getUser().remove(user); - } - - try { - // save the file - save(); - } catch (Exception e) { - throw new AuthorityAccessException(e.getMessage(), e); - } - } - - /** - * Grants access to download content regardless of FlowFile attributes. - */ - @Override - public DownloadAuthorization authorizeDownload(List dnChain, Map attributes) throws UnknownIdentityException, AuthorityAccessException { - return DownloadAuthorization.approved(); - } - - private User getUser(String dn) throws UnknownIdentityException { - // ensure the DN was specified - if (dn == null) { - throw new UnknownIdentityException("User DN not specified."); - } - - // attempt to get the user and ensure it was located - User desiredUser = null; - for (final User user : users.getUser()) { - if (dn.equalsIgnoreCase(user.getDn())) { - desiredUser = user; - break; - } - } - - return desiredUser; - } - - private Collection getUserGroup(String group) throws UnknownIdentityException { - // ensure the DN was specified - if (group == null) { - throw new UnknownIdentityException("User group not specified."); - } - - // get all users with this group - Collection userGroup = null; - for (final User user : users.getUser()) { - if (group.equals(user.getGroup())) { - if (userGroup == null) { - userGroup = new HashSet<>(); - } - userGroup.add(user); - } - } - - return userGroup; - } - - private void save() throws Exception { - final Marshaller marshaller = JAXB_CONTEXT.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - - // save users to restore directory before primary directory - if (restoreUsersFile != null) { - marshaller.marshal(users, restoreUsersFile); - } - - // save users to primary directory - marshaller.marshal(users, usersFile); - } - - @AuthorityProviderContext - public void setNiFiProperties(NiFiProperties properties) { - this.properties = properties; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/xsd/users.xsd b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/xsd/users.xsd deleted file mode 100644 index 4ee1e17226..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/xsd/users.xsd +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/test/java/org/apache/nifi/authorization/FileAuthorizationProviderTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/test/java/org/apache/nifi/authorization/FileAuthorizationProviderTest.java deleted file mode 100644 index 74285003b4..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/test/java/org/apache/nifi/authorization/FileAuthorizationProviderTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.authorization; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.util.file.FileUtils; -import org.apache.nifi.util.NiFiProperties; -import org.junit.After; -import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; -import org.junit.Ignore; -import org.mockito.Mockito; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@Ignore -public class FileAuthorizationProviderTest { - - private FileAuthorizationProvider provider; - - private File primary; - - private File restore; - - private NiFiProperties mockProperties; - - private AuthorityProviderConfigurationContext mockConfigurationContext; - - @Before - public void setup() throws IOException { - - primary = new File("target/primary/users.txt"); - restore = new File("target/restore/users.txt"); - - System.out.println("absolute path: " + primary.getAbsolutePath()); - - mockProperties = mock(NiFiProperties.class); - when(mockProperties.getRestoreDirectory()).thenReturn(restore.getParentFile()); - - mockConfigurationContext = mock(AuthorityProviderConfigurationContext.class); - when(mockConfigurationContext.getProperty(Mockito.eq("Authorized Users File"))).thenReturn(primary.getPath()); - - provider = new FileAuthorizationProvider(); - provider.setNiFiProperties(mockProperties); - provider.initialize(null); - } - - @After - public void cleanup() throws Exception { - deleteFile(primary); - deleteFile(restore); - } - - private boolean deleteFile(final File file) { - if (file.isDirectory()) { - FileUtils.deleteFilesInDir(file, null, null, true, true); - } - return FileUtils.deleteFile(file, null, 10); - } - - @Test - public void testPostContructionWhenRestoreDoesNotExist() throws Exception { - - byte[] primaryBytes = "".getBytes(); - FileOutputStream fos = new FileOutputStream(primary); - fos.write(primaryBytes); - fos.close(); - - provider.onConfigured(mockConfigurationContext); - assertEquals(primary.length(), restore.length()); - } - - @Test - public void testPostContructionWhenPrimaryDoesNotExist() throws Exception { - - byte[] restoreBytes = "".getBytes(); - FileOutputStream fos = new FileOutputStream(restore); - fos.write(restoreBytes); - fos.close(); - - provider.onConfigured(mockConfigurationContext); - assertEquals(restore.length(), primary.length()); - - } - - @Test(expected = ProviderCreationException.class) - public void testPostContructionWhenPrimaryDifferentThanRestore() throws Exception { - - byte[] primaryBytes = "".getBytes(); - FileOutputStream fos = new FileOutputStream(primary); - fos.write(primaryBytes); - fos.close(); - - byte[] restoreBytes = "".getBytes(); - fos = new FileOutputStream(restore); - fos.write(restoreBytes); - fos.close(); - - provider.onConfigured(mockConfigurationContext); - } - - @Test - public void testPostContructionWhenPrimaryAndBackupDoNotExist() throws Exception { - - provider.onConfigured(mockConfigurationContext); - assertEquals(0, restore.length()); - assertEquals(restore.length(), primary.length()); - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorizer/src/main/java/org/apache/nifi/authorization/FileAuthorizer.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorizer/src/main/java/org/apache/nifi/authorization/FileAuthorizer.java index 174e501bea..8529caf149 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorizer/src/main/java/org/apache/nifi/authorization/FileAuthorizer.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorizer/src/main/java/org/apache/nifi/authorization/FileAuthorizer.java @@ -19,7 +19,7 @@ package org.apache.nifi.authorization; import org.apache.commons.lang3.StringUtils; import org.apache.nifi.authorization.annotation.AuthorizerContext; import org.apache.nifi.authorization.exception.AuthorizationAccessException; -import org.apache.nifi.authorization.exception.ProviderCreationException; +import org.apache.nifi.authorization.exception.AuthorizerCreationException; import org.apache.nifi.authorization.generated.Authorization; import org.apache.nifi.authorization.generated.Resource; import org.apache.nifi.authorization.generated.Resources; @@ -85,21 +85,21 @@ public class FileAuthorizer implements Authorizer { private final AtomicReference>>> authorizations = new AtomicReference<>(); @Override - public void initialize(final AuthorizerInitializationContext initializationContext) throws ProviderCreationException { + public void initialize(final AuthorizerInitializationContext initializationContext) throws AuthorizerCreationException { } @Override - public void onConfigured(final AuthorizerConfigurationContext configurationContext) throws ProviderCreationException { + public void onConfigured(final AuthorizerConfigurationContext configurationContext) throws AuthorizerCreationException { try { final PropertyValue authorizationsPath = configurationContext.getProperty("Authorizations File"); if (StringUtils.isBlank(authorizationsPath.getValue())) { - throw new ProviderCreationException("The authorizations file must be specified."); + throw new AuthorizerCreationException("The authorizations file must be specified."); } // get the authorizations file and ensure it exists authorizationsFile = new File(authorizationsPath.getValue()); if (!authorizationsFile.exists()) { - throw new ProviderCreationException("The authorizations file must exist."); + throw new AuthorizerCreationException("The authorizations file must exist."); } final File authorizationsFileDirectory = authorizationsFile.getAbsoluteFile().getParentFile(); @@ -112,7 +112,7 @@ public class FileAuthorizer implements Authorizer { // check that restore directory is not the same as the primary directory if (authorizationsFileDirectory.getAbsolutePath().equals(restoreDirectory.getAbsolutePath())) { - throw new ProviderCreationException(String.format("Authorizations file directory '%s' is the same as restore directory '%s' ", + throw new AuthorizerCreationException(String.format("Authorizations file directory '%s' is the same as restore directory '%s' ", authorizationsFileDirectory.getAbsolutePath(), restoreDirectory.getAbsolutePath())); } @@ -123,7 +123,7 @@ public class FileAuthorizer implements Authorizer { // sync the primary copy with the restore copy FileUtils.syncWithRestore(authorizationsFile, restoreAuthorizationsFile, logger); } catch (final IOException | IllegalStateException ioe) { - throw new ProviderCreationException(ioe); + throw new AuthorizerCreationException(ioe); } } @@ -160,8 +160,8 @@ public class FileAuthorizer implements Authorizer { } } }, reloadInterval, reloadInterval, TimeUnit.MILLISECONDS); - } catch (IOException | ProviderCreationException | SAXException | JAXBException | IllegalStateException e) { - throw new ProviderCreationException(e); + } catch (IOException | AuthorizerCreationException | SAXException | JAXBException | IllegalStateException e) { + throw new AuthorizerCreationException(e); } } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorizer/src/test/java/org/apache/nifi/authorization/FileAuthorizerTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorizer/src/test/java/org/apache/nifi/authorization/FileAuthorizerTest.java index 359d45baf8..bfb064a075 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorizer/src/test/java/org/apache/nifi/authorization/FileAuthorizerTest.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorizer/src/test/java/org/apache/nifi/authorization/FileAuthorizerTest.java @@ -18,7 +18,7 @@ package org.apache.nifi.authorization; import org.apache.nifi.attribute.expression.language.StandardPropertyValue; import org.apache.nifi.authorization.AuthorizationResult.Result; -import org.apache.nifi.authorization.exception.ProviderCreationException; +import org.apache.nifi.authorization.exception.AuthorizerCreationException; import org.apache.nifi.authorization.resource.ResourceFactory; import org.apache.nifi.util.NiFiProperties; import org.apache.nifi.util.file.FileUtils; @@ -111,20 +111,20 @@ public class FileAuthorizerTest { assertEquals(primary.length(), restore.length()); } - @Test(expected = ProviderCreationException.class) + @Test(expected = AuthorizerCreationException.class) public void testPostConstructionWhenPrimaryDoesNotExist() throws Exception { writeAuthorizationsFile(restore, EMPTY_AUTHORIZATIONS_CONCISE); authorizer.onConfigured(configurationContext); } - @Test(expected = ProviderCreationException.class) + @Test(expected = AuthorizerCreationException.class) public void testPostConstructionWhenPrimaryDifferentThanRestore() throws Exception { writeAuthorizationsFile(primary, EMPTY_AUTHORIZATIONS); writeAuthorizationsFile(restore, EMPTY_AUTHORIZATIONS_CONCISE); authorizer.onConfigured(configurationContext); } - @Test(expected = ProviderCreationException.class) + @Test(expected = AuthorizerCreationException.class) public void testBadSchema() throws Exception { writeAuthorizationsFile(primary, BAD_SCHEMA_AUTHORIZATIONS); authorizer.onConfigured(configurationContext); @@ -135,7 +135,8 @@ public class FileAuthorizerTest { writeAuthorizationsFile(primary, AUTHORIZATIONS); authorizer.onConfigured(configurationContext); - final AuthorizationRequest request = new AuthorizationRequest.Builder().resource(ResourceFactory.getFlowResource()).identity("user-1").action(RequestAction.READ).build(); + final AuthorizationRequest request = new AuthorizationRequest.Builder().resource(ResourceFactory.getFlowResource()).identity("user-1").anonymous(false).accessAttempt(true).action(RequestAction + .READ).build(); final AuthorizationResult result = authorizer.authorize(request); assertTrue(Result.Approved.equals(result.getResult())); } @@ -145,7 +146,8 @@ public class FileAuthorizerTest { writeAuthorizationsFile(primary, AUTHORIZATIONS); authorizer.onConfigured(configurationContext); - final AuthorizationRequest request = new AuthorizationRequest.Builder().resource(ResourceFactory.getFlowResource()).identity("user-2").action(RequestAction.READ).build(); + final AuthorizationRequest request = + new AuthorizationRequest.Builder().resource(ResourceFactory.getFlowResource()).identity("user-2").anonymous(false).accessAttempt(true).action(RequestAction.READ).build(); final AuthorizationResult result = authorizer.authorize(request); assertFalse(Result.Approved.equals(result.getResult())); } @@ -155,7 +157,8 @@ public class FileAuthorizerTest { writeAuthorizationsFile(primary, AUTHORIZATIONS); authorizer.onConfigured(configurationContext); - final AuthorizationRequest request = new AuthorizationRequest.Builder().resource(ResourceFactory.getFlowResource()).identity("user-1").action(RequestAction.WRITE).build(); + final AuthorizationRequest request = + new AuthorizationRequest.Builder().resource(ResourceFactory.getFlowResource()).identity("user-1").anonymous(false).accessAttempt(true).action(RequestAction.WRITE).build(); final AuthorizationResult result = authorizer.authorize(request); assertFalse(Result.Approved.equals(result.getResult())); } @@ -167,7 +170,8 @@ public class FileAuthorizerTest { authorizer.onConfigured(configurationContext); // ensure the user currently does not have write access - final AuthorizationRequest request = new AuthorizationRequest.Builder().resource(ResourceFactory.getFlowResource()).identity("user-1").action(RequestAction.WRITE).build(); + final AuthorizationRequest request = + new AuthorizationRequest.Builder().resource(ResourceFactory.getFlowResource()).identity("user-1").anonymous(false).accessAttempt(true).action(RequestAction.WRITE).build(); AuthorizationResult result = authorizer.authorize(request); assertFalse(Result.Approved.equals(result.getResult())); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java index 81ee5a018c..ee59942e0d 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java @@ -410,12 +410,28 @@ public interface ProcessGroup { */ Set getConnections(); + /** + * @param id of the Connection + * @return the Connection with the given ID, if it exists as a child or + * descendant of this ProcessGroup. This performs a recursive search of all + * descendant ProcessGroups + */ + Connection findConnection(String id); + /** * @return a List of all Connections contains within this ProcessGroup and * any child ProcessGroups */ List findAllConnections(); + /** + * @param id of the Funnel + * @return the Funnel with the given ID, if it exists as a child or + * descendant of this ProcessGroup. This performs a recursive search of all + * descendant ProcessGroups + */ + Funnel findFunnel(String id); + /** * Adds the given RemoteProcessGroup to this ProcessGroup * @@ -520,6 +536,14 @@ public interface ProcessGroup { */ List findAllProcessors(); + /** + * @param id of the Label + * @return the Label with the given ID, if it exists as a child or + * descendant of this ProcessGroup. This performs a recursive search of all + * descendant ProcessGroups + */ + Label findLabel(String id); + /** * @return a List of all Labels that are children or descendants of this * ProcessGroup. This performsn a recursive search of all descendant diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java index 9f14354529..75395b726f 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java @@ -53,7 +53,7 @@ import javax.net.ssl.SSLContext; import org.apache.commons.lang3.StringUtils; import org.apache.nifi.action.Action; import org.apache.nifi.admin.service.AuditService; -import org.apache.nifi.admin.service.UserService; +import org.apache.nifi.admin.service.KeyService; import org.apache.nifi.annotation.lifecycle.OnAdded; import org.apache.nifi.annotation.lifecycle.OnConfigurationRestored; import org.apache.nifi.annotation.lifecycle.OnRemoved; @@ -257,7 +257,7 @@ public class FlowController implements EventAccess, ControllerServiceProvider, R private final AtomicReference counterRepositoryRef; private final AtomicBoolean initialized = new AtomicBoolean(false); private final ControllerServiceProvider controllerServiceProvider; - private final UserService userService; + private final KeyService keyService; private final AuditService auditService; private final EventDrivenWorkerQueue eventDrivenWorkerQueue; private final ComponentStatusRepository componentStatusRepository; @@ -354,13 +354,13 @@ public class FlowController implements EventAccess, ControllerServiceProvider, R public static FlowController createStandaloneInstance( final FlowFileEventRepository flowFileEventRepo, final NiFiProperties properties, - final UserService userService, + final KeyService keyService, final AuditService auditService, final StringEncryptor encryptor) { return new FlowController( flowFileEventRepo, properties, - userService, + keyService, auditService, encryptor, /* configuredForClustering */ false, @@ -370,14 +370,14 @@ public class FlowController implements EventAccess, ControllerServiceProvider, R public static FlowController createClusteredInstance( final FlowFileEventRepository flowFileEventRepo, final NiFiProperties properties, - final UserService userService, + final KeyService keyService, final AuditService auditService, final StringEncryptor encryptor, final NodeProtocolSender protocolSender) { final FlowController flowController = new FlowController( flowFileEventRepo, properties, - userService, + keyService, auditService, encryptor, /* configuredForClustering */ true, @@ -391,7 +391,7 @@ public class FlowController implements EventAccess, ControllerServiceProvider, R private FlowController( final FlowFileEventRepository flowFileEventRepo, final NiFiProperties properties, - final UserService userService, + final KeyService keyService, final AuditService auditService, final StringEncryptor encryptor, final boolean configuredForClustering, @@ -447,7 +447,7 @@ public class FlowController implements EventAccess, ControllerServiceProvider, R startConnectablesAfterInitialization = new ArrayList<>(); startRemoteGroupPortsAfterInitialization = new ArrayList<>(); - this.userService = userService; + this.keyService = keyService; this.auditService = auditService; final String gracefulShutdownSecondsVal = properties.getProperty(GRACEFUL_SHUTDOWN_PERIOD); @@ -1032,7 +1032,7 @@ public class FlowController implements EventAccess, ControllerServiceProvider, R name = requireNonNull(name).intern(); verifyPortIdDoesNotExist(id); return new StandardRootGroupPort(id, name, null, TransferDirection.RECEIVE, ConnectableType.INPUT_PORT, - userService, getBulletinRepository(), processScheduler, Boolean.TRUE.equals(isSiteToSiteSecure)); + keyService, getBulletinRepository(), processScheduler, Boolean.TRUE.equals(isSiteToSiteSecure)); } /** @@ -1049,7 +1049,7 @@ public class FlowController implements EventAccess, ControllerServiceProvider, R name = requireNonNull(name).intern(); verifyPortIdDoesNotExist(id); return new StandardRootGroupPort(id, name, null, TransferDirection.SEND, ConnectableType.OUTPUT_PORT, - userService, getBulletinRepository(), processScheduler, Boolean.TRUE.equals(isSiteToSiteSecure)); + keyService, getBulletinRepository(), processScheduler, Boolean.TRUE.equals(isSiteToSiteSecure)); } /** diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java index 4646d55d35..71e51b6e00 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java @@ -944,6 +944,27 @@ public final class StandardProcessGroup implements ProcessGroup { } } + @Override + public Connection findConnection(final String id) { + return findConnection(id, this); + } + + private Connection findConnection(final String id, final ProcessGroup start) { + Connection connection = start.getConnection(id); + if (connection != null) { + return connection; + } + + for (final ProcessGroup group : start.getProcessGroups()) { + connection = findConnection(id, group); + if (connection != null) { + return connection; + } + } + + return null; + } + @Override public List findAllConnections() { return findAllConnections(this); @@ -1475,6 +1496,27 @@ public final class StandardProcessGroup implements ProcessGroup { return null; } + @Override + public Label findLabel(final String id) { + return findLabel(id, this); + } + + private Label findLabel(final String id, final ProcessGroup start) { + Label label = start.getLabel(id); + if (label != null) { + return label; + } + + for (final ProcessGroup group : start.getProcessGroups()) { + label = findLabel(id, group); + if (label != null) { + return label; + } + } + + return null; + } + @Override public List - + @@ -110,7 +110,7 @@ - + @@ -129,7 +129,7 @@ - + @@ -181,42 +181,49 @@ - + + + + + + + + + + + + + - + - + - + - + - + - - - - - - + @@ -225,6 +232,14 @@ + + + + + + + + @@ -234,16 +249,6 @@ - - - - - - - - - - @@ -265,7 +270,6 @@ - @@ -275,7 +279,6 @@ - diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/AccessTokenEndpointTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/AccessTokenEndpointTest.java index fe484901c1..5b96c6e52f 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/AccessTokenEndpointTest.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/AccessTokenEndpointTest.java @@ -41,11 +41,13 @@ import org.apache.nifi.web.util.WebUtils; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; /** * Access token endpoint test. */ +@Ignore public class AccessTokenEndpointTest { private static final String CLIENT_ID = "token-endpoint-id"; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/AdminAccessControlTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/AdminAccessControlTest.java index 8e0efd1d29..dd69954f4b 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/AdminAccessControlTest.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/AdminAccessControlTest.java @@ -53,11 +53,13 @@ import org.apache.commons.collections4.CollectionUtils; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; /** * Access control test for the admin user. */ +@Ignore public class AdminAccessControlTest { public static final String ADMIN_USER_DN = "CN=Lastname Firstname Middlename admin, OU=Unknown, OU=Unknown, OU=Unknown, O=Unknown, C=Unknown"; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/DfmAccessControlTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/DfmAccessControlTest.java index 283a4a928c..914cf600fa 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/DfmAccessControlTest.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/DfmAccessControlTest.java @@ -78,6 +78,7 @@ import org.junit.Test; /** * Access control test for the dfm user. */ +@Ignore public class DfmAccessControlTest { public static final String DFM_USER_DN = "CN=Lastname Firstname Middlename dfm, OU=Unknown, OU=Unknown, OU=Unknown, O=Unknown, C=Unknown"; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/ReadOnlyAccessControlTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/ReadOnlyAccessControlTest.java index 0ab074fe5b..2ed653a9e4 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/ReadOnlyAccessControlTest.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/ReadOnlyAccessControlTest.java @@ -49,11 +49,13 @@ import org.apache.nifi.web.api.entity.ProcessorsEntity; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; /** * Access control test for a read only user. */ +@Ignore public class ReadOnlyAccessControlTest { public static final String READ_ONLY_USER_DN = "CN=Lastname Firstname Middlename monitor, OU=Unknown, OU=Unknown, OU=Unknown, O=Unknown, C=Unknown"; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestAuthorizationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestAuthorizationProvider.java deleted file mode 100644 index aa8a51827c..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestAuthorizationProvider.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.integration.util; - -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.authorization.AuthorityProvider; -import org.apache.nifi.authorization.AuthorityProviderConfigurationContext; -import org.apache.nifi.authorization.AuthorityProviderInitializationContext; -import org.apache.nifi.authorization.exception.AuthorityAccessException; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.authorization.exception.UnknownIdentityException; -import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.authorization.DownloadAuthorization; - -/** - * - */ -public class NiFiTestAuthorizationProvider implements AuthorityProvider { - - private final Map> users; - - /** - * Creates a new FileAuthorizationProvider. - */ - public NiFiTestAuthorizationProvider() { - users = new HashMap<>(); - users.put("CN=localhost, OU=Apache NiFi, O=Apache, L=Santa Monica, ST=CA, C=US", EnumSet.of(Authority.ROLE_PROXY)); - users.put("CN=Lastname Firstname Middlename monitor, OU=Unknown, OU=Unknown, OU=Unknown, O=Unknown, C=Unknown", EnumSet.of(Authority.ROLE_MONITOR)); - users.put("CN=Lastname Firstname Middlename dfm, OU=Unknown, OU=Unknown, OU=Unknown, O=Unknown, C=Unknown", EnumSet.of(Authority.ROLE_DFM)); - users.put("CN=Lastname Firstname Middlename admin, OU=Unknown, OU=Unknown, OU=Unknown, O=Unknown, C=Unknown", EnumSet.of(Authority.ROLE_ADMIN)); - users.put("user@nifi", EnumSet.of(Authority.ROLE_DFM)); - } - - @Override - public void initialize(AuthorityProviderInitializationContext initializationContext) throws ProviderCreationException { - } - - @Override - public void onConfigured(AuthorityProviderConfigurationContext configurationContext) throws ProviderCreationException { - } - - @Override - public void preDestruction() { - } - - private void checkDn(String dn) throws UnknownIdentityException { - if (!users.containsKey(dn)) { - throw new UnknownIdentityException("Unknown user: " + dn); - } - } - - /** - * Determines if the specified dn is known to this authority provider. - * - * @param dn dn - * @return True if he dn is known, false otherwise - */ - @Override - public boolean doesDnExist(String dn) throws AuthorityAccessException { - try { - checkDn(dn); - return true; - } catch (UnknownIdentityException uie) { - return false; - } - } - - /** - * Loads the authorities for the specified user. - * - * @param dn dn - * @return authorities - * @throws UnknownIdentityException ex - * @throws AuthorityAccessException ex - */ - @Override - public Set getAuthorities(String dn) throws UnknownIdentityException, AuthorityAccessException { - checkDn(dn); - return new HashSet<>(users.get(dn)); - } - - /** - * Sets the specified authorities to the specified user. - * - * @param dn dn - * @param authorities authorities - * @throws AuthorityAccessException ex - */ - @Override - public void setAuthorities(String dn, Set authorities) throws UnknownIdentityException, AuthorityAccessException { - } - - /** - * Adds the specified user. - * - * @param dn dn - * @param group group - * @throws UnknownIdentityException ex - * @throws AuthorityAccessException ex - */ - @Override - public void addUser(String dn, String group) throws AuthorityAccessException { - } - - /** - * Gets the users for the specified authority. - * - * @param authority authority - * @return users - * @throws AuthorityAccessException ex - */ - @Override - public Set getUsers(Authority authority) throws AuthorityAccessException { - Set usersForAuthority = new HashSet<>(); - for (String dn : users.keySet()) { - if (users.get(dn).contains(authority)) { - usersForAuthority.add(dn); - } - } - return usersForAuthority; - } - - /** - * Removes the specified user. - * - * @param dn dn - * @throws UnknownIdentityException ex - * @throws AuthorityAccessException ex - */ - @Override - public void revokeUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - } - - @Override - public String getGroupForUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - return StringUtils.EMPTY; - } - - @Override - public void revokeGroup(String group) throws UnknownIdentityException, AuthorityAccessException { - } - - @Override - public void setUsersGroup(Set dn, String group) throws UnknownIdentityException, AuthorityAccessException { - } - - @Override - public void ungroupUser(String dn) throws UnknownIdentityException, AuthorityAccessException { - } - - @Override - public void ungroup(String group) throws UnknownIdentityException, AuthorityAccessException { - } - - @Override - public DownloadAuthorization authorizeDownload(List dnChain, Map attributes) throws UnknownIdentityException, AuthorityAccessException { - return DownloadAuthorization.approved(); - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestAuthorizer.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestAuthorizer.java new file mode 100644 index 0000000000..5795b6915a --- /dev/null +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestAuthorizer.java @@ -0,0 +1,56 @@ +/* + * 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. + */ +package org.apache.nifi.integration.util; + +import org.apache.nifi.authorization.AuthorizationRequest; +import org.apache.nifi.authorization.AuthorizationResult; +import org.apache.nifi.authorization.Authorizer; +import org.apache.nifi.authorization.AuthorizerConfigurationContext; +import org.apache.nifi.authorization.AuthorizerInitializationContext; +import org.apache.nifi.authorization.exception.AuthorizationAccessException; +import org.apache.nifi.authorization.exception.AuthorizerCreationException; + +/** + * + */ +public class NiFiTestAuthorizer implements Authorizer { + + + /** + * Creates a new FileAuthorizationProvider. + */ + public NiFiTestAuthorizer() { + } + + @Override + public void initialize(AuthorizerInitializationContext initializationContext) throws AuthorizerCreationException { + } + + @Override + public void onConfigured(AuthorizerConfigurationContext configurationContext) throws AuthorizerCreationException { + } + + @Override + public AuthorizationResult authorize(AuthorizationRequest request) throws AuthorizationAccessException { + return AuthorizationResult.approved(); + } + + @Override + public void preDestruction() { + } + +} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestLoginIdentityProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestLoginIdentityProvider.java index c023ce1f6f..967f65225d 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestLoginIdentityProvider.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestLoginIdentityProvider.java @@ -16,10 +16,6 @@ */ package org.apache.nifi.integration.util; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import org.apache.nifi.authorization.exception.ProviderCreationException; import org.apache.nifi.authentication.AuthenticationResponse; import org.apache.nifi.authentication.LoginCredentials; import org.apache.nifi.authentication.LoginIdentityProvider; @@ -27,6 +23,11 @@ import org.apache.nifi.authentication.LoginIdentityProviderConfigurationContext; import org.apache.nifi.authentication.LoginIdentityProviderInitializationContext; import org.apache.nifi.authentication.exception.IdentityAccessException; import org.apache.nifi.authentication.exception.InvalidLoginCredentialsException; +import org.apache.nifi.authentication.exception.ProviderCreationException; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; /** * diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestServer.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestServer.java index 38c2d4153e..4c1a4173f1 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestServer.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/util/NiFiTestServer.java @@ -79,7 +79,7 @@ public class NiFiTestServer { org.eclipse.jetty.util.ssl.SslContextFactory contextFactory = new org.eclipse.jetty.util.ssl.SslContextFactory(); // require client auth when not supporting login or anonymous access - if (StringUtils.isBlank(properties.getProperty(NiFiProperties.SECURITY_USER_LOGIN_IDENTITY_PROVIDER)) && properties.getAnonymousAuthorities().isEmpty()) { + if (StringUtils.isBlank(properties.getProperty(NiFiProperties.SECURITY_USER_LOGIN_IDENTITY_PROVIDER))) { contextFactory.setNeedClientAuth(true); } else { contextFactory.setWantClientAuth(true); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider deleted file mode 100644 index dcdc53edc6..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider +++ /dev/null @@ -1,15 +0,0 @@ -# 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. -org.apache.nifi.integration.util.NiFiTestAuthorizationProvider \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/META-INF/services/org.apache.nifi.authorization.Authorizer old mode 100755 new mode 100644 similarity index 93% rename from nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider rename to nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/META-INF/services/org.apache.nifi.authorization.Authorizer index 93d2941bc4..e7d65f492c --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-file-authorization-provider/src/main/resources/META-INF/services/org.apache.nifi.authorization.AuthorityProvider +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/META-INF/services/org.apache.nifi.authorization.Authorizer @@ -12,4 +12,4 @@ # 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. -org.apache.nifi.authorization.FileAuthorizationProvider +org.apache.nifi.integration.util.NiFiTestAuthorizer \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/access-control/authority-providers.xml b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/access-control/authority-providers.xml index 418f717652..a3fb0888fc 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/access-control/authority-providers.xml +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/access-control/authority-providers.xml @@ -19,6 +19,6 @@ test-provider - org.apache.nifi.integration.util.NiFiTestAuthorizationProvider + org.apache.nifi.integration.util.NiFiTestAuthorizer \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/access-control/nifi.properties b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/access-control/nifi.properties index 1726a074a0..e655f06631 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/access-control/nifi.properties +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/resources/access-control/nifi.properties @@ -98,12 +98,8 @@ nifi.security.truststore=target/test-classes/access-control/localhost-ts.jks nifi.security.truststoreType=JKS nifi.security.truststorePasswd=localtest nifi.security.needClientAuth=true -nifi.security.user.authority.provider=test-provider nifi.security.user.login.identity.provider=test-provider -nifi.security.authorizedUsers.file=target/test-classes/access-control/users.xml -nifi.security.user.credential.cache.duration=1 hr -nifi.security.support.new.account.requests= -nifi.security.anonymous.authorities= +nifi.security.user.authorizer= # cluster common properties (cluster manager and nodes must have same values) # nifi.cluster.protocol.heartbeat.interval=5 sec diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationFilter.java index 0520ac80ea..7108edb5e6 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationFilter.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationFilter.java @@ -25,19 +25,15 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.user.NiFiUser; import org.apache.nifi.util.NiFiProperties; -import org.apache.nifi.web.security.token.NiFiAuthorizationRequestToken; import org.apache.nifi.web.security.user.NiFiUserUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.security.authentication.AccountStatusException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.filter.GenericFilterBean; /** @@ -65,72 +61,41 @@ public abstract class NiFiAuthenticationFilter extends GenericFilterBean { } private boolean requiresAuthentication(final HttpServletRequest request) { - // continue attempting authorization if the user is anonymous - if (isAnonymousUser()) { - return true; - } - - // or there is no user yet - return NiFiUserUtils.getNiFiUser() == null && NiFiUserUtils.getNewAccountRequest() == null; - } - - private boolean isAnonymousUser() { - final NiFiUser user = NiFiUserUtils.getNiFiUser(); - return user != null && NiFiUser.ANONYMOUS_USER_IDENTITY.equals(user.getIdentity()); + return NiFiUserUtils.getNiFiUser() == null; } private void authenticate(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException { String dnChain = null; try { - final NiFiAuthorizationRequestToken authenticated = attemptAuthentication(request); - if (authenticated != null) { - dnChain = ProxiedEntitiesUtils.formatProxyDn(StringUtils.join(authenticated.getChain(), "><")); - + final Authentication authenticationRequest = attemptAuthentication(request); + if (authenticationRequest != null) { // log the request attempt - response details will be logged later - log.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", dnChain, request.getMethod(), + log.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", authenticationRequest.toString(), request.getMethod(), request.getRequestURL().toString(), request.getRemoteAddr())); // attempt to authorize the user - final Authentication authorized = authenticationManager.authenticate(authenticated); - successfulAuthorization(request, response, authorized); + final Authentication authenticated = authenticationManager.authenticate(authenticationRequest); + successfulAuthorization(request, response, authenticated); } // continue chain.doFilter(request, response); - } catch (final InvalidAuthenticationException iae) { - // invalid authentication - always error out - unsuccessfulAuthorization(request, response, iae); } catch (final AuthenticationException ae) { - // other authentication exceptions... if we are already the anonymous user, allow through otherwise error out - if (isAnonymousUser()) { - if (dnChain == null) { - log.info(String.format("Continuing as anonymous user. Unable to authenticate %s: %s", dnChain, ae)); - } else { - log.info(String.format("Continuing as anonymous user. Unable to authenticate: %s", ae)); - } - - chain.doFilter(request, response); - } else { - unsuccessfulAuthorization(request, response, ae); - } + // invalid authentication - always error out + unsuccessfulAuthorization(request, response, ae); } } /** - * Attempt to authenticate the client making the request. If the request does not contain an authentication attempt, this method should return null. If the request contains an authentication - * request, the implementation should convert it to a NiFiAuthorizationRequestToken (which is used when authorizing the client). Implementations should throw InvalidAuthenticationException when - * the request contains an authentication request but it could not be authenticated. + * Attempt to extract an authentication attempt from the specified request. * * @param request The request - * @return The NiFiAutorizationRequestToken used to later authorized the client - * @throws InvalidAuthenticationException If the request contained an authentication attempt, but could not authenticate + * @return The authentication attempt or null if none is found int he request */ - public abstract NiFiAuthorizationRequestToken attemptAuthentication(HttpServletRequest request); + public abstract Authentication attemptAuthentication(HttpServletRequest request); protected void successfulAuthorization(HttpServletRequest request, HttpServletResponse response, Authentication authResult) { - if (log.isDebugEnabled()) { - log.debug("Authentication success: " + authResult); - } + log.info("Authentication success for " + authResult); SecurityContextHolder.getContext().setAuthentication(authResult); ProxiedEntitiesUtils.successfulAuthorization(request, response, authResult); @@ -147,20 +112,9 @@ public abstract class NiFiAuthenticationFilter extends GenericFilterBean { PrintWriter out = response.getWriter(); // use the type of authentication exception to determine the response code - if (ae instanceof UsernameNotFoundException) { - if (properties.getSupportNewAccountRequests()) { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - out.println("Not authorized."); - } else { - response.setStatus(HttpServletResponse.SC_FORBIDDEN); - out.println("Access is denied."); - } - } else if (ae instanceof InvalidAuthenticationException) { + if (ae instanceof InvalidAuthenticationException) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); out.println(ae.getMessage()); - } else if (ae instanceof AccountStatusException) { - response.setStatus(HttpServletResponse.SC_FORBIDDEN); - out.println(ae.getMessage()); } else if (ae instanceof UntrustedProxyException) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); out.println(ae.getMessage()); @@ -183,39 +137,6 @@ public abstract class NiFiAuthenticationFilter extends GenericFilterBean { } } - /** - * Determines if the specified request is attempting to register a new user account. - * - * @param request http request - * @return true if new user - */ - protected final boolean isNewAccountRequest(HttpServletRequest request) { - if ("POST".equalsIgnoreCase(request.getMethod())) { - String path = request.getPathInfo(); - if (StringUtils.isNotBlank(path)) { - if ("/controller/users".equals(path)) { - return true; - } - } - } - return false; - } - - /** - * Extracts the justification from the specified request. - * - * @param request The request - * @return The justification - */ - protected final String getJustification(HttpServletRequest request) { - // get the justification - String justification = request.getParameter("justification"); - if (justification == null) { - justification = StringUtils.EMPTY; - } - return justification; - } - @Override public void destroy() { } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationProvider.java deleted file mode 100644 index e51a26e61c..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/NiFiAuthenticationProvider.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.web.security; - -import org.apache.nifi.web.security.token.NewAccountAuthorizationRequestToken; -import org.apache.nifi.web.security.token.NewAccountAuthorizationToken; -import org.apache.nifi.web.security.token.NiFiAuthorizationRequestToken; -import org.apache.nifi.web.security.token.NiFiAuthorizationToken; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UsernameNotFoundException; - -/** - * - */ -public class NiFiAuthenticationProvider implements AuthenticationProvider { - - private final AuthenticationUserDetailsService userDetailsService; - - public NiFiAuthenticationProvider(final AuthenticationUserDetailsService userDetailsService) { - this.userDetailsService = userDetailsService; - } - - @Override - public Authentication authenticate(Authentication authentication) throws AuthenticationException { - final NiFiAuthorizationRequestToken request = (NiFiAuthorizationRequestToken) authentication; - - try { - // defer to the nifi user details service to authorize the user - final UserDetails userDetails = userDetailsService.loadUserDetails(request); - - // build a token for accesing nifi - final NiFiAuthorizationToken result = new NiFiAuthorizationToken(userDetails); - result.setDetails(request.getDetails()); - return result; - } catch (final UsernameNotFoundException unfe) { - // if the authorization request is for a new account and it could not be authorized because the user was not found, - // return the token so the new account could be created. this must go here to ensure that any proxies have been authorized - if (isNewAccountAuthenticationToken(request)) { - return new NewAccountAuthorizationToken(((NewAccountAuthorizationRequestToken) authentication).getNewAccountRequest()); - } else { - throw unfe; - } - } - } - - private boolean isNewAccountAuthenticationToken(final Authentication authentication) { - return NewAccountAuthorizationRequestToken.class.isAssignableFrom(authentication.getClass()); - } - - @Override - public boolean supports(Class authentication) { - return NiFiAuthorizationRequestToken.class.isAssignableFrom(authentication); - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/anonymous/NiFiAnonymousUserFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/anonymous/NiFiAnonymousUserFilter.java index 05c5fb86d5..3f4562924f 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/anonymous/NiFiAnonymousUserFilter.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/anonymous/NiFiAnonymousUserFilter.java @@ -16,20 +16,17 @@ */ package org.apache.nifi.web.security.anonymous; -import java.util.EnumSet; -import javax.servlet.http.HttpServletRequest; -import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.admin.service.UserService; -import org.apache.nifi.authorization.Authority; +import org.apache.nifi.admin.service.KeyService; import org.apache.nifi.user.NiFiUser; +import org.apache.nifi.web.security.token.NiFiAuthenticationToken; import org.apache.nifi.web.security.user.NiFiUserDetails; -import org.apache.nifi.web.security.token.NiFiAuthorizationToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; +import javax.servlet.http.HttpServletRequest; + /** * Custom AnonymouseAuthenticationFilter used to grant additional authorities depending on the current operating mode. */ @@ -39,7 +36,7 @@ public class NiFiAnonymousUserFilter extends AnonymousAuthenticationFilter { private static final String ANONYMOUS_KEY = "anonymousNifiKey"; - private UserService userService; + private KeyService keyService; public NiFiAnonymousUserFilter() { super(ANONYMOUS_KEY); @@ -47,40 +44,12 @@ public class NiFiAnonymousUserFilter extends AnonymousAuthenticationFilter { @Override protected Authentication createAuthentication(HttpServletRequest request) { - Authentication authentication = null; - - try { - // load the anonymous user from the database - NiFiUser user = userService.getUserByDn(NiFiUser.ANONYMOUS_USER_IDENTITY); - - // if this is an unsecure request allow full access - if (!request.isSecure()) { - user.getAuthorities().addAll(EnumSet.allOf(Authority.class)); - } - - // only create an authentication token if the anonymous user has some authorities or they are accessing a ui - // extension. ui extensions have run this security filter but we shouldn't require authentication/authorization - // when accessing static resources like images, js, and css. authentication/authorization is required when - // interacting with nifi however and that will be verified in the NiFiWebContext or NiFiWebConfigurationContext - if (!user.getAuthorities().isEmpty() || !request.getContextPath().startsWith("/nifi-api")) { - NiFiUserDetails userDetails = new NiFiUserDetails(user); - - // get the granted authorities - authentication = new NiFiAuthorizationToken(userDetails); - } - } catch (AdministrationException ase) { - // record the issue - anonymousUserFilterLogger.warn("Unable to load anonymous user from accounts database: " + ase.getMessage()); - if (anonymousUserFilterLogger.isDebugEnabled()) { - anonymousUserFilterLogger.warn(StringUtils.EMPTY, ase); - } - } - return authentication; + return new NiFiAuthenticationToken(new NiFiUserDetails(NiFiUser.ANONYMOUS)); } /* setters */ - public void setUserService(UserService userService) { - this.userService = userService; + public void setKeyService(KeyService keyService) { + this.keyService = keyService; } } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationService.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationService.java deleted file mode 100644 index dd87cfa194..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationService.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.web.security.authorization; - -import java.util.ArrayList; -import java.util.List; -import java.util.ListIterator; -import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.admin.service.AccountDisabledException; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AccountPendingException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.admin.service.UserService; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.user.NiFiUser; -import org.apache.nifi.util.NiFiProperties; -import org.apache.nifi.web.security.UntrustedProxyException; -import org.apache.nifi.web.security.user.NiFiUserDetails; -import org.apache.nifi.web.security.token.NiFiAuthorizationRequestToken; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.dao.DataAccessException; -import org.springframework.security.authentication.AccountStatusException; -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UsernameNotFoundException; - -/** - * UserDetailsService that will verify user identity and grant user authorities. - */ -public class NiFiAuthorizationService implements AuthenticationUserDetailsService { - - private static final Logger logger = LoggerFactory.getLogger(NiFiAuthorizationService.class); - - private UserService userService; - private NiFiProperties properties; - - /** - * Loads the user details for the specified dn. - * - * Synchronizing because we want each request to be authorized atomically since each may contain any number of DNs. We wanted an access decision made for each individual request as a whole - * (without other request potentially impacting it). - * - * @param request request - * @return user details - * @throws UsernameNotFoundException ex - * @throws org.springframework.dao.DataAccessException ex - */ - @Override - public synchronized UserDetails loadUserDetails(NiFiAuthorizationRequestToken request) throws UsernameNotFoundException, DataAccessException { - NiFiUserDetails userDetails = null; - final List chain = new ArrayList<>(request.getChain()); - - // ensure valid input - if (chain.isEmpty()) { - logger.warn("Malformed proxy chain: " + StringUtils.join(request.getChain())); - throw new UntrustedProxyException("Malformed proxy chain."); - } - - NiFiUser proxy = null; - - // process each part of the proxy chain - for (final ListIterator chainIter = request.getChain().listIterator(chain.size()); chainIter.hasPrevious();) { - final String dn = chainIter.previous(); - - // if there is another dn after this one, this dn is a proxy for the request - if (chainIter.hasPrevious()) { - try { - // get the user details for the proxy - final NiFiUserDetails proxyDetails = getNiFiUserDetails(dn); - final NiFiUser user = proxyDetails.getNiFiUser(); - - // verify the proxy has the appropriate role - if (!user.getAuthorities().contains(Authority.ROLE_PROXY)) { - logger.warn(String.format("Proxy '%s' must have '%s' authority. Current authorities: %s", dn, Authority.ROLE_PROXY.toString(), StringUtils.join(user.getAuthorities(), ", "))); - throw new UntrustedProxyException(String.format("Untrusted proxy '%s' must be authorized with '%s'.", dn, Authority.ROLE_PROXY.toString())); - } - - // if we've already encountered a proxy, update the chain - if (proxy != null) { - user.setChain(proxy); - } - - // record this user as the proxy for the next user in the chain - proxy = user; - } catch (UsernameNotFoundException unfe) { - // if this proxy is a new user, conditionally create a new account automatically - if (properties.getSupportNewAccountRequests()) { - try { - logger.warn(String.format("Automatic account request generated for unknown proxy: %s", dn)); - - // attempt to create a new user account for the proxying client - userService.createPendingUserAccount(dn, "Automatic account request generated for unknown proxy."); - } catch (AdministrationException ae) { - throw new AuthenticationServiceException(String.format("Unable to create an account request for '%s': %s", dn, ae.getMessage()), ae); - } catch (IllegalArgumentException iae) { - // check then modified... account didn't exist when getting the user details but did when - // attempting to auto create the user account request - final String message = String.format("Account request was already submitted for '%s'", dn); - logger.warn(message); - throw new AccountStatusException(message) { - }; - } - } - - logger.warn(String.format("Untrusted proxy '%s' must be authorized with '%s' authority: %s", dn, Authority.ROLE_PROXY.toString(), unfe.getMessage())); - throw new UntrustedProxyException(String.format("Untrusted proxy '%s' must be authorized with '%s'.", dn, Authority.ROLE_PROXY.toString())); - } catch (AuthenticationException ae) { - logger.warn(String.format("Untrusted proxy '%s' must be authorized with '%s' authority: %s", dn, Authority.ROLE_PROXY.toString(), ae.getMessage())); - throw new UntrustedProxyException(String.format("Untrusted proxy '%s' must be authorized with '%s'.", dn, Authority.ROLE_PROXY.toString())); - } - } else { - userDetails = getNiFiUserDetails(dn); - - // if we've already encountered a proxy, update the chain - if (proxy != null) { - final NiFiUser user = userDetails.getNiFiUser(); - user.setChain(proxy); - } - } - } - - return userDetails; - } - - /** - * Loads the user details for the specified dn. - * - * @param dn user dn - * @return user detail - */ - private NiFiUserDetails getNiFiUserDetails(String dn) { - try { - NiFiUser user = userService.checkAuthorization(dn); - return new NiFiUserDetails(user); - } catch (AdministrationException ase) { - throw new AuthenticationServiceException(String.format("An error occurred while accessing the user credentials for '%s': %s", dn, ase.getMessage()), ase); - } catch (AccountDisabledException | AccountPendingException e) { - throw new AccountStatusException(e.getMessage(), e) { - }; - } catch (AccountNotFoundException anfe) { - throw new UsernameNotFoundException(anfe.getMessage()); - } - } - - /* setters */ - public void setUserService(UserService userService) { - this.userService = userService; - } - - public void setProperties(NiFiProperties properties) { - this.properties = properties; - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationFilter.java index bd468e4705..4f7383e93b 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationFilter.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationFilter.java @@ -16,18 +16,13 @@ */ package org.apache.nifi.web.security.jwt; -import io.jsonwebtoken.JwtException; import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.web.security.InvalidAuthenticationException; import org.apache.nifi.web.security.NiFiAuthenticationFilter; -import org.apache.nifi.web.security.token.NewAccountAuthorizationRequestToken; -import org.apache.nifi.web.security.token.NiFiAuthorizationRequestToken; -import org.apache.nifi.web.security.user.NewAccountRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; import javax.servlet.http.HttpServletRequest; -import java.util.Arrays; /** */ @@ -36,12 +31,11 @@ public class JwtAuthenticationFilter extends NiFiAuthenticationFilter { private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class); public static final String AUTHORIZATION = "Authorization"; - - private JwtService jwtService; + public static final String BEARER = "Bearer "; @Override - public NiFiAuthorizationRequestToken attemptAuthentication(final HttpServletRequest request) { - // only suppport jwt login when running securely + public Authentication attemptAuthentication(final HttpServletRequest request) { + // only support jwt login when running securely if (!request.isSecure()) { return null; } @@ -52,28 +46,12 @@ public class JwtAuthenticationFilter extends NiFiAuthenticationFilter { final String authorization = request.getHeader(AUTHORIZATION); // if there is no authorization header, we don't know the user - if (authorization == null || !StringUtils.startsWith(authorization, "Bearer ")) { + if (authorization == null || !StringUtils.startsWith(authorization, BEARER)) { return null; } else { // Extract the Base64 encoded token from the Authorization header final String token = StringUtils.substringAfterLast(authorization, " "); - - try { - final String jwtPrincipal = jwtService.getAuthenticationFromToken(token); - - if (isNewAccountRequest(request)) { - return new NewAccountAuthorizationRequestToken(new NewAccountRequest(Arrays.asList(jwtPrincipal), getJustification(request))); - } else { - return new NiFiAuthorizationRequestToken(Arrays.asList(jwtPrincipal)); - } - } catch (JwtException e) { - throw new InvalidAuthenticationException(e.getMessage(), e); - } + return new JwtAuthenticationRequestToken(token); } } - - public void setJwtService(JwtService jwtService) { - this.jwtService = jwtService; - } - } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationProvider.java new file mode 100644 index 0000000000..289cc87ed5 --- /dev/null +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationProvider.java @@ -0,0 +1,56 @@ +/* + * 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. + */ +package org.apache.nifi.web.security.jwt; + +import io.jsonwebtoken.JwtException; +import org.apache.nifi.user.NiFiUser; +import org.apache.nifi.web.security.InvalidAuthenticationException; +import org.apache.nifi.web.security.token.NiFiAuthenticationToken; +import org.apache.nifi.web.security.user.NiFiUserDetails; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; + +/** + * + */ +public class JwtAuthenticationProvider implements AuthenticationProvider { + + private final JwtService jwtService; + + public JwtAuthenticationProvider(JwtService jwtService) { + this.jwtService = jwtService; + } + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + final JwtAuthenticationRequestToken request = (JwtAuthenticationRequestToken) authentication; + + try { + final String jwtPrincipal = jwtService.getAuthenticationFromToken(request.getToken()); + final NiFiUser user = new NiFiUser(jwtPrincipal); + return new NiFiAuthenticationToken(new NiFiUserDetails(user)); + } catch (JwtException e) { + throw new InvalidAuthenticationException(e.getMessage(), e); + } + } + + @Override + public boolean supports(Class authentication) { + return JwtAuthenticationRequestToken.class.isAssignableFrom(authentication); + } +} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NewAccountAuthorizationToken.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationRequestToken.java similarity index 59% rename from nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NewAccountAuthorizationToken.java rename to nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationRequestToken.java index de0fde66bc..0be30bfb99 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NewAccountAuthorizationToken.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtAuthenticationRequestToken.java @@ -14,23 +14,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.nifi.web.security.token; +package org.apache.nifi.web.security.jwt; -import org.apache.nifi.web.security.user.NewAccountRequest; import org.springframework.security.authentication.AbstractAuthenticationToken; /** - * This is an Authentication Token for a user that has been authenticated but is not authorized to access the NiFi APIs. Typically, this authentication token is used successfully when requesting a - * NiFi account. Requesting any other endpoint would be rejected due to lack of roles. + * This is an authentication request with a given JWT token. */ -public class NewAccountAuthorizationToken extends AbstractAuthenticationToken { +public class JwtAuthenticationRequestToken extends AbstractAuthenticationToken { - final NewAccountRequest newAccountRequest; + private final String token; - public NewAccountAuthorizationToken(final NewAccountRequest newAccountRequest) { + /** + * Creates a representation of the jwt authentication request for a user. + * + * @param token The unique token for this user + */ + public JwtAuthenticationRequestToken(final String token) { super(null); - super.setAuthenticated(true); - this.newAccountRequest = newAccountRequest; + setAuthenticated(false); + this.token = token; } @Override @@ -40,7 +43,16 @@ public class NewAccountAuthorizationToken extends AbstractAuthenticationToken { @Override public Object getPrincipal() { - return newAccountRequest; + return token; + } + + public String getToken() { + return token; + } + + @Override + public String toString() { + return getName(); } } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtService.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtService.java index dd6a17ade3..bd581419fe 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtService.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/jwt/JwtService.java @@ -29,7 +29,7 @@ import io.jsonwebtoken.SigningKeyResolverAdapter; import io.jsonwebtoken.UnsupportedJwtException; import org.apache.commons.lang3.StringUtils; import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.admin.service.UserService; +import org.apache.nifi.admin.service.KeyService; import org.apache.nifi.key.Key; import org.apache.nifi.web.security.token.LoginAuthenticationToken; import org.slf4j.LoggerFactory; @@ -48,10 +48,10 @@ public class JwtService { private static final String KEY_ID_CLAIM = "kid"; private static final String USERNAME_CLAIM = "preferred_username"; - private final UserService userService; + private final KeyService keyService; - public JwtService(final UserService userService) { - this.userService = userService; + public JwtService(final KeyService keyService) { + this.keyService = keyService; } public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException { @@ -90,7 +90,7 @@ public class JwtService { // Get the key based on the key id in the claims final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class); - final Key key = userService.getKey(keyId); + final Key key = keyService.getKey(keyId); // Ensure we were able to find a key that was previously issued by this key service for this user if (key == null || key.getKey() == null) { @@ -136,7 +136,7 @@ public class JwtService { try { // Get/create the key for this user - final Key key = userService.getOrCreateKey(identity); + final Key key = keyService.getOrCreateKey(identity); final byte[] keyBytes = key.getKey().getBytes(StandardCharsets.UTF_8); logger.trace("Generating JWT for " + authenticationToken); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/node/NodeAuthorizedUserFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/node/NodeAuthorizedUserFilter.java index a3e6c3c1b0..03e1400cf8 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/node/NodeAuthorizedUserFilter.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/node/NodeAuthorizedUserFilter.java @@ -30,7 +30,7 @@ import org.apache.nifi.authentication.AuthenticationResponse; import org.apache.nifi.web.security.user.NiFiUserDetails; import org.apache.nifi.user.NiFiUser; import org.apache.nifi.util.NiFiProperties; -import org.apache.nifi.web.security.token.NiFiAuthorizationToken; +import org.apache.nifi.web.security.token.NiFiAuthenticationToken; import org.apache.nifi.web.security.x509.X509CertificateExtractor; import org.apache.nifi.web.security.x509.X509IdentityProvider; import org.apache.nifi.web.util.WebUtils; @@ -96,7 +96,7 @@ public class NodeAuthorizedUserFilter extends GenericFilterBean { httpServletRequest.getRequestURL().toString(), request.getRemoteAddr())); // create the authorized nifi token - final NiFiAuthorizationToken token = new NiFiAuthorizationToken(userDetails); + final NiFiAuthenticationToken token = new NiFiAuthenticationToken(userDetails); SecurityContextHolder.getContext().setAuthentication(token); } } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationFilter.java index 7cf3eeb977..5f5a3cdaac 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationFilter.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationFilter.java @@ -16,14 +16,12 @@ */ package org.apache.nifi.web.security.otp; -import org.apache.nifi.web.security.InvalidAuthenticationException; import org.apache.nifi.web.security.NiFiAuthenticationFilter; -import org.apache.nifi.web.security.token.NiFiAuthorizationRequestToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; import javax.servlet.http.HttpServletRequest; -import java.util.Arrays; import java.util.regex.Pattern; /** @@ -41,10 +39,8 @@ public class OtpAuthenticationFilter extends NiFiAuthenticationFilter { protected static final String ACCESS_TOKEN = "access_token"; - private OtpService otpService; - @Override - public NiFiAuthorizationRequestToken attemptAuthentication(final HttpServletRequest request) { + public Authentication attemptAuthentication(final HttpServletRequest request) { // only support otp login when running securely if (!request.isSecure()) { return null; @@ -57,27 +53,18 @@ public class OtpAuthenticationFilter extends NiFiAuthenticationFilter { if (accessToken == null) { return null; } else { - try { - String identity = null; - if (request.getContextPath().equals("/nifi-api")) { - if (isDownloadRequest(request.getPathInfo())) { - // handle download requests - identity = otpService.getAuthenticationFromDownloadToken(accessToken); - } - } else { - // handle requests to other context paths (other UI extensions) - identity = otpService.getAuthenticationFromUiExtensionToken(accessToken); + if (request.getContextPath().equals("/nifi-api")) { + if (isDownloadRequest(request.getPathInfo())) { + // handle download requests + return new OtpAuthenticationRequestToken(accessToken, true); } - - // the path is a support path for otp tokens - if (identity == null) { - return null; - } - - return new NiFiAuthorizationRequestToken(Arrays.asList(identity)); - } catch (final OtpAuthenticationException oae) { - throw new InvalidAuthenticationException(oae.getMessage(), oae); + } else { + // handle requests to other context paths (other UI extensions) + return new OtpAuthenticationRequestToken(accessToken, false); } + + // the path is a support path for otp tokens + return null; } } @@ -85,8 +72,4 @@ public class OtpAuthenticationFilter extends NiFiAuthenticationFilter { return PROVENANCE_DOWNLOAD_PATTERN.matcher(pathInfo).matches() || QUEUE_DOWNLOAD_PATTERN.matcher(pathInfo).matches() || TEMPLATE_DOWNLOAD_PATTERN.matcher(pathInfo).matches(); } - public void setOtpService(OtpService otpService) { - this.otpService = otpService; - } - } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationProvider.java new file mode 100644 index 0000000000..411efc11e5 --- /dev/null +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationProvider.java @@ -0,0 +1,60 @@ +/* + * 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. + */ +package org.apache.nifi.web.security.otp; + +import org.apache.nifi.user.NiFiUser; +import org.apache.nifi.web.security.InvalidAuthenticationException; +import org.apache.nifi.web.security.token.NiFiAuthenticationToken; +import org.apache.nifi.web.security.user.NiFiUserDetails; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; + +/** + * + */ +public class OtpAuthenticationProvider implements AuthenticationProvider { + + private OtpService otpService; + + public OtpAuthenticationProvider(OtpService otpService) { + this.otpService = otpService; + } + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + final OtpAuthenticationRequestToken request = (OtpAuthenticationRequestToken) authentication; + + try { + final String otpPrincipal; + if (request.isDownloadToken()) { + otpPrincipal = otpService.getAuthenticationFromDownloadToken(request.getToken()); + } else { + otpPrincipal = otpService.getAuthenticationFromUiExtensionToken(request.getToken()); + } + final NiFiUser user = new NiFiUser(otpPrincipal); + return new NiFiAuthenticationToken(new NiFiUserDetails(user)); + } catch (OtpAuthenticationException e) { + throw new InvalidAuthenticationException(e.getMessage(), e); + } + } + + @Override + public boolean supports(Class authentication) { + return OtpAuthenticationRequestToken.class.isAssignableFrom(authentication); + } +} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NiFiAuthorizationRequestToken.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationRequestToken.java similarity index 57% rename from nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NiFiAuthorizationRequestToken.java rename to nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationRequestToken.java index c20aaf394e..e5dd6eefa6 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NiFiAuthorizationRequestToken.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/otp/OtpAuthenticationRequestToken.java @@ -14,23 +14,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.nifi.web.security.token; +package org.apache.nifi.web.security.otp; -import java.util.Collections; -import java.util.List; import org.springframework.security.authentication.AbstractAuthenticationToken; /** - * An authentication token that is used as an authorization request. The request has already been authenticated and is now going to be authorized. - * The request chain is specified during creation and is used authorize the user(s). + * This is an authentication request with a given OTP token. */ -public class NiFiAuthorizationRequestToken extends AbstractAuthenticationToken { +public class OtpAuthenticationRequestToken extends AbstractAuthenticationToken { - private final List chain; + private final String token; + private final boolean isDownloadToken; - public NiFiAuthorizationRequestToken(final List chain) { + /** + * Creates a representation of the otp authentication request for a user. + * + * @param token The unique token for this user + */ + public OtpAuthenticationRequestToken(final String token, final boolean isDownloadToken) { super(null); - this.chain = chain; + setAuthenticated(false); + this.token = token; + this.isDownloadToken = isDownloadToken; } @Override @@ -40,15 +45,20 @@ public class NiFiAuthorizationRequestToken extends AbstractAuthenticationToken { @Override public Object getPrincipal() { - return chain; + return token; } - public List getChain() { - return Collections.unmodifiableList(chain); + public String getToken() { + return token; + } + + public boolean isDownloadToken() { + return isDownloadToken; } @Override - public final void setAuthenticated(boolean authenticated) { - throw new IllegalArgumentException("Cannot change the authenticated state."); + public String toString() { + return getName(); } + } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/kerberos/KerberosServiceFactoryBean.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/spring/KerberosServiceFactoryBean.java similarity index 94% rename from nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/kerberos/KerberosServiceFactoryBean.java rename to nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/spring/KerberosServiceFactoryBean.java index 8b834a1209..bbe15d120e 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/kerberos/KerberosServiceFactoryBean.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/spring/KerberosServiceFactoryBean.java @@ -14,9 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.nifi.web.security.kerberos; +package org.apache.nifi.web.security.spring; import org.apache.nifi.util.NiFiProperties; +import org.apache.nifi.web.security.kerberos.AlternateKerberosUserDetailsService; +import org.apache.nifi.web.security.kerberos.KerberosService; import org.springframework.beans.factory.FactoryBean; import org.springframework.core.io.FileSystemResource; import org.springframework.security.kerberos.authentication.KerberosServiceAuthenticationProvider; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/spring/LoginIdentityProviderFactoryBean.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/spring/LoginIdentityProviderFactoryBean.java index 92a27aeff9..2ee187adf4 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/spring/LoginIdentityProviderFactoryBean.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/spring/LoginIdentityProviderFactoryBean.java @@ -16,21 +16,6 @@ */ package org.apache.nifi.web.security.spring; -import java.io.File; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; import org.apache.commons.lang3.StringUtils; import org.apache.nifi.authentication.AuthenticationResponse; import org.apache.nifi.authentication.LoginCredentials; @@ -39,11 +24,11 @@ import org.apache.nifi.authentication.LoginIdentityProviderConfigurationContext; import org.apache.nifi.authentication.LoginIdentityProviderInitializationContext; import org.apache.nifi.authentication.LoginIdentityProviderLookup; import org.apache.nifi.authentication.annotation.LoginIdentityProviderContext; +import org.apache.nifi.authentication.exception.ProviderCreationException; +import org.apache.nifi.authentication.exception.ProviderDestructionException; import org.apache.nifi.authentication.generated.LoginIdentityProviders; import org.apache.nifi.authentication.generated.Property; import org.apache.nifi.authentication.generated.Provider; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.authorization.exception.ProviderDestructionException; import org.apache.nifi.nar.ExtensionManager; import org.apache.nifi.nar.NarCloseable; import org.apache.nifi.util.NiFiProperties; @@ -53,6 +38,22 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.xml.sax.SAXException; +import javax.xml.XMLConstants; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import java.io.File; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + /** * */ diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NewAccountAuthorizationRequestToken.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NewAccountAuthorizationRequestToken.java deleted file mode 100644 index 693d420386..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NewAccountAuthorizationRequestToken.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.web.security.token; - -import org.apache.nifi.web.security.user.NewAccountRequest; - -/** - * An authentication token that is used as an authorization request when submitting a new account. - */ -public class NewAccountAuthorizationRequestToken extends NiFiAuthorizationRequestToken { - - final NewAccountRequest newAccountRequest; - - public NewAccountAuthorizationRequestToken(final NewAccountRequest newAccountRequest) { - super(newAccountRequest.getChain()); - this.newAccountRequest = newAccountRequest; - } - - public String getJustification() { - return newAccountRequest.getJustification(); - } - - public NewAccountRequest getNewAccountRequest() { - return newAccountRequest; - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NiFiAuthorizationToken.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NiFiAuthenticationToken.java similarity index 92% rename from nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NiFiAuthorizationToken.java rename to nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NiFiAuthenticationToken.java index 0cb0353a53..f7964f55f6 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NiFiAuthorizationToken.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/token/NiFiAuthenticationToken.java @@ -22,11 +22,11 @@ import org.springframework.security.core.userdetails.UserDetails; /** * An authentication token that represents an Authenticated and Authorized user of the NiFi Apis. The authorities are based off the specified UserDetails. */ -public class NiFiAuthorizationToken extends AbstractAuthenticationToken { +public class NiFiAuthenticationToken extends AbstractAuthenticationToken { final UserDetails nifiUserDetails; - public NiFiAuthorizationToken(final UserDetails nifiUserDetails) { + public NiFiAuthenticationToken(final UserDetails nifiUserDetails) { super(nifiUserDetails.getAuthorities()); super.setAuthenticated(true); setDetails(nifiUserDetails); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NewAccountRequest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NewAccountRequest.java deleted file mode 100644 index 3ec147a88e..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NewAccountRequest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.web.security.user; - -import java.util.List; - -/** - * - */ -public class NewAccountRequest { - - private final List chain; - private final String justification; - - public NewAccountRequest(final List chain, final String justification) { - this.chain = chain; - this.justification = justification; - } - - public List getChain() { - return chain; - } - - public String getJustification() { - return justification; - } - - public String getUsername() { - // the end user is the first item in the chain - return chain.get(0); - } - -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NiFiUserDetails.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NiFiUserDetails.java index b559269a4d..86668fe5c3 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NiFiUserDetails.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NiFiUserDetails.java @@ -16,16 +16,14 @@ */ package org.apache.nifi.web.security.user; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.user.NiFiUser; import org.apache.commons.lang3.StringUtils; +import org.apache.nifi.user.NiFiUser; import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; +import java.util.Collection; +import java.util.Collections; + /** * User details for a NiFi user. */ @@ -58,12 +56,7 @@ public class NiFiUserDetails implements UserDetails { */ @Override public Collection getAuthorities() { - final Set authorities = user.getAuthorities(); - final Set grantedAuthorities = new HashSet<>(authorities.size()); - for (final Authority authority : authorities) { - grantedAuthorities.add(new SimpleGrantedAuthority(authority.toString())); - } - return grantedAuthorities; + return Collections.EMPTY_SET; } @Override diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NiFiUserUtils.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NiFiUserUtils.java index 341663e1cd..255b3d5195 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NiFiUserUtils.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/user/NiFiUserUtils.java @@ -77,27 +77,6 @@ public final class NiFiUserUtils { return user; } - /** - * Returns the NewAccountRequest or null if this is not a new account request. - * - * @return new account request - */ - public static NewAccountRequest getNewAccountRequest() { - NewAccountRequest newAccountRequest = null; - - // obtain the principal in the current authentication - final SecurityContext context = SecurityContextHolder.getContext(); - final Authentication authentication = context.getAuthentication(); - if (authentication != null) { - Object principal = authentication.getPrincipal(); - if (principal instanceof NewAccountRequest) { - newAccountRequest = (NewAccountRequest) principal; - } - } - - return newAccountRequest; - } - public static String getNiFiUserName() { // get the nifi user to extract the username NiFiUser user = NiFiUserUtils.getNiFiUser(); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationFilter.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationFilter.java index 019a53c9ed..ab6ceec28f 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationFilter.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationFilter.java @@ -16,18 +16,15 @@ */ package org.apache.nifi.web.security.x509; -import java.security.cert.X509Certificate; -import java.util.List; -import javax.servlet.http.HttpServletRequest; -import org.apache.nifi.authentication.AuthenticationResponse; -import org.apache.nifi.web.security.InvalidAuthenticationException; import org.apache.nifi.web.security.NiFiAuthenticationFilter; import org.apache.nifi.web.security.ProxiedEntitiesUtils; -import org.apache.nifi.web.security.token.NewAccountAuthorizationRequestToken; -import org.apache.nifi.web.security.token.NiFiAuthorizationRequestToken; -import org.apache.nifi.web.security.user.NewAccountRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor; + +import javax.servlet.http.HttpServletRequest; +import java.security.cert.X509Certificate; /** * Custom X509 filter that will inspect the HTTP headers for a proxied user before extracting the user details from the client certificate. @@ -37,10 +34,10 @@ public class X509AuthenticationFilter extends NiFiAuthenticationFilter { private static final Logger logger = LoggerFactory.getLogger(X509AuthenticationFilter.class); private X509CertificateExtractor certificateExtractor; - private X509IdentityProvider certificateIdentityProvider; + private X509PrincipalExtractor principalExtractor; @Override - public NiFiAuthorizationRequestToken attemptAuthentication(final HttpServletRequest request) { + public Authentication attemptAuthentication(final HttpServletRequest request) { // only suppport x509 login when running securely if (!request.isSecure()) { return null; @@ -52,20 +49,7 @@ public class X509AuthenticationFilter extends NiFiAuthenticationFilter { return null; } - // attempt to authenticate if certificates were found - final AuthenticationResponse authenticationResponse; - try { - authenticationResponse = certificateIdentityProvider.authenticate(certificates); - } catch (final IllegalArgumentException iae) { - throw new InvalidAuthenticationException(iae.getMessage(), iae); - } - - final List proxyChain = ProxiedEntitiesUtils.buildProxiedEntitiesChain(request, authenticationResponse.getIdentity()); - if (isNewAccountRequest(request)) { - return new NewAccountAuthorizationRequestToken(new NewAccountRequest(proxyChain, getJustification(request))); - } else { - return new NiFiAuthorizationRequestToken(proxyChain); - } + return new X509AuthenticationRequestToken(request.getHeader(ProxiedEntitiesUtils.PROXY_ENTITIES_CHAIN), principalExtractor, certificates); } /* setters */ @@ -73,8 +57,8 @@ public class X509AuthenticationFilter extends NiFiAuthenticationFilter { this.certificateExtractor = certificateExtractor; } - public void setCertificateIdentityProvider(X509IdentityProvider certificateIdentityProvider) { - this.certificateIdentityProvider = certificateIdentityProvider; + public void setPrincipalExtractor(X509PrincipalExtractor principalExtractor) { + this.principalExtractor = principalExtractor; } } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationProvider.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationProvider.java new file mode 100644 index 0000000000..2593f92380 --- /dev/null +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationProvider.java @@ -0,0 +1,78 @@ +/* + * 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. + */ +package org.apache.nifi.web.security.x509; + +import org.apache.commons.lang3.StringUtils; +import org.apache.nifi.authentication.AuthenticationResponse; +import org.apache.nifi.user.NiFiUser; +import org.apache.nifi.web.security.InvalidAuthenticationException; +import org.apache.nifi.web.security.ProxiedEntitiesUtils; +import org.apache.nifi.web.security.token.NiFiAuthenticationToken; +import org.apache.nifi.web.security.user.NiFiUserDetails; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; + +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; + +/** + * + */ +public class X509AuthenticationProvider implements AuthenticationProvider { + + private X509IdentityProvider certificateIdentityProvider; + + public X509AuthenticationProvider(X509IdentityProvider certificateIdentityProvider) { + this.certificateIdentityProvider = certificateIdentityProvider; + } + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + final X509AuthenticationRequestToken request = (X509AuthenticationRequestToken) authentication; + + // attempt to authenticate if certificates were found + final AuthenticationResponse authenticationResponse; + try { + authenticationResponse = certificateIdentityProvider.authenticate(request.getCertificates()); + } catch (final IllegalArgumentException iae) { + throw new InvalidAuthenticationException(iae.getMessage(), iae); + } + + if (StringUtils.isBlank(request.getProxiedEntitiesChain())) { + return new NiFiAuthenticationToken(new NiFiUserDetails(new NiFiUser(authenticationResponse.getIdentity(), authenticationResponse.getUsername(), null))); + } else { + // build the entire proxy chain if applicable - + final List proxyChain = new ArrayList<>(ProxiedEntitiesUtils.tokenizeProxiedEntitiesChain(request.getProxiedEntitiesChain())); + proxyChain.add(authenticationResponse.getIdentity()); + + // add the chain as appropriate to each proxy + NiFiUser proxy = null; + for (final ListIterator chainIter = proxyChain.listIterator(proxyChain.size()); chainIter.hasPrevious();) { + proxy = new NiFiUser(chainIter.previous(), proxy); + } + + return new NiFiAuthenticationToken(new NiFiUserDetails(proxy)); + } + } + + @Override + public boolean supports(Class authentication) { + return X509AuthenticationRequestToken.class.isAssignableFrom(authentication); + } +} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationRequestToken.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationRequestToken.java new file mode 100644 index 0000000000..cec72fef8c --- /dev/null +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/X509AuthenticationRequestToken.java @@ -0,0 +1,75 @@ +/* + * 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. + */ +package org.apache.nifi.web.security.x509; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor; + +import java.security.cert.X509Certificate; + +/** + * This is an authentication request with a given JWT token. + */ +public class X509AuthenticationRequestToken extends AbstractAuthenticationToken { + + private final String proxiedEntitiesChain; + private final X509PrincipalExtractor principalExtractor; + private final X509Certificate[] certificates; + + /** + * Creates a representation of the jwt authentication request for a user. + * + * @param proxiedEntitiesChain The http servlet request + * @param certificates The certificate chain + */ + public X509AuthenticationRequestToken(final String proxiedEntitiesChain, final X509PrincipalExtractor principalExtractor, final X509Certificate[] certificates) { + super(null); + setAuthenticated(false); + this.proxiedEntitiesChain = proxiedEntitiesChain; + this.principalExtractor = principalExtractor; + this.certificates = certificates; + } + + @Override + public Object getCredentials() { + return null; + } + + @Override + public Object getPrincipal() { + if (StringUtils.isBlank(proxiedEntitiesChain)) { + return principalExtractor.extractPrincipal(certificates[0]); + } else { + return String.format("%s<%s>", proxiedEntitiesChain, principalExtractor.extractPrincipal(certificates[0])); + } + } + + public String getProxiedEntitiesChain() { + return proxiedEntitiesChain; + } + + public X509Certificate[] getCertificates() { + return certificates; + } + + @Override + public String toString() { + return getName(); + } + +} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/ocsp/OcspCertificateValidator.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/ocsp/OcspCertificateValidator.java index b0762b5c12..108926ce57 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/ocsp/OcspCertificateValidator.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/java/org/apache/nifi/web/security/x509/ocsp/OcspCertificateValidator.java @@ -121,9 +121,8 @@ public class OcspCertificateValidator { trustedCAs.put(ocspCertificate.getSubjectX500Principal().getName(), ocspCertificate); } - // determine how long to cache the ocsp responses for - final String rawCacheDurationDuration = properties.getUserCredentialCacheDuration(); - final long cacheDurationMillis = FormatUtils.getTimeDuration(rawCacheDurationDuration, TimeUnit.MILLISECONDS); + // TODO - determine how long to cache the ocsp responses for + final long cacheDurationMillis = FormatUtils.getTimeDuration("12 hours", TimeUnit.MILLISECONDS); // build the ocsp cache ocspCache = CacheBuilder.newBuilder().expireAfterWrite(cacheDurationMillis, TimeUnit.MILLISECONDS).build(new CacheLoader() { diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/resources/nifi-web-security-context.xml b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/resources/nifi-web-security-context.xml index 4e24badc61..12d8594a24 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/resources/nifi-web-security-context.xml +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/main/resources/nifi-web-security-context.xml @@ -39,22 +39,31 @@ - - - - + + + - + + + + + + + + + + + - + diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationServiceTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationServiceTest.java deleted file mode 100644 index 23b49b7236..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/authorization/NiFiAuthorizationServiceTest.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * 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. - */ -package org.apache.nifi.web.security.authorization; - -import java.util.Arrays; -import org.apache.nifi.admin.service.AccountDisabledException; -import org.apache.nifi.admin.service.AccountNotFoundException; -import org.apache.nifi.admin.service.AccountPendingException; -import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.admin.service.UserService; -import org.apache.nifi.authorization.Authority; -import org.apache.nifi.user.NiFiUser; -import org.apache.nifi.util.NiFiProperties; -import org.apache.nifi.web.security.UntrustedProxyException; -import org.apache.nifi.web.security.token.NiFiAuthorizationRequestToken; -import org.apache.nifi.web.security.user.NiFiUserDetails; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.springframework.security.authentication.AccountStatusException; -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.security.core.userdetails.UsernameNotFoundException; - -/** - * Test case for NiFiAuthorizationService. - */ -public class NiFiAuthorizationServiceTest { - - private static final String USER = "user"; - private static final String PROXY = "proxy"; - private static final String PROXY_PROXY = "proxy-proxy"; - private static final String USER_NOT_FOUND = "user-not-found"; - private static final String USER_DISABLED = "user-disabled"; - private static final String USER_PENDING = "user-pending"; - private static final String USER_ADMIN_EXCEPTION = "user-admin-exception"; - private static final String PROXY_NOT_FOUND = "proxy-not-found"; - - private NiFiAuthorizationService authorizationService; - private UserService userService; - - @Before - public void setup() throws Exception { - // mock the web security properties - final NiFiProperties properties = Mockito.mock(NiFiProperties.class); - Mockito.when(properties.getSupportNewAccountRequests()).thenReturn(Boolean.TRUE); - - userService = Mockito.mock(UserService.class); - Mockito.doReturn(null).when(userService).createPendingUserAccount(Mockito.anyString(), Mockito.anyString()); - Mockito.doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String identity = (String) args[0]; - - if (null != identity) { - switch (identity) { - case USER_NOT_FOUND: - case PROXY_NOT_FOUND: - throw new AccountNotFoundException(""); - case USER_DISABLED: - throw new AccountDisabledException(""); - case USER_PENDING: - throw new AccountPendingException(""); - case USER_ADMIN_EXCEPTION: - throw new AdministrationException(); - case USER: - final NiFiUser monitor = new NiFiUser(); - monitor.setIdentity(identity); - monitor.getAuthorities().add(Authority.ROLE_MONITOR); - return monitor; - case PROXY: - case PROXY_PROXY: - final NiFiUser proxy = new NiFiUser(); - proxy.setIdentity(identity); - proxy.getAuthorities().add(Authority.ROLE_PROXY); - return proxy; - } - } - - return null; - } - }).when(userService).checkAuthorization(Mockito.anyString()); - - // create the authorization service - authorizationService = new NiFiAuthorizationService(); - authorizationService.setProperties(properties); - authorizationService.setUserService(userService); - } - - private NiFiAuthorizationRequestToken createRequestAuthentication(final String... identities) { - return new NiFiAuthorizationRequestToken(Arrays.asList(identities)); - } - - /** - * Ensures the authorization service correctly handles users invalid identity chain. - * - * @throws Exception ex - */ - @Test(expected = UntrustedProxyException.class) - public void testInvalidDnChain() throws Exception { - authorizationService.loadUserDetails(createRequestAuthentication()); - } - - /** - * Ensures the authorization service correctly handles account not found. - * - * @throws Exception ex - */ - @Test(expected = UsernameNotFoundException.class) - public void testAccountNotFound() throws Exception { - authorizationService.loadUserDetails(createRequestAuthentication(USER_NOT_FOUND)); - } - - /** - * Ensures the authorization service correctly handles account disabled. - * - * @throws Exception ex - */ - @Test(expected = AccountStatusException.class) - public void testAccountDisabled() throws Exception { - authorizationService.loadUserDetails(createRequestAuthentication(USER_DISABLED)); - } - - /** - * Ensures the authorization service correctly handles account pending. - * - * @throws Exception ex - */ - @Test(expected = AccountStatusException.class) - public void testAccountPending() throws Exception { - authorizationService.loadUserDetails(createRequestAuthentication(USER_PENDING)); - } - - /** - * Ensures the authorization service correctly handles account administration exception. - * - * @throws Exception ex - */ - @Test(expected = AuthenticationServiceException.class) - public void testAccountAdminException() throws Exception { - authorizationService.loadUserDetails(createRequestAuthentication(USER_ADMIN_EXCEPTION)); - } - - /** - * Tests the case when there is no proxy. - * - * @throws Exception ex - */ - @Test - public void testNoProxy() throws Exception { - final NiFiUserDetails details = (NiFiUserDetails) authorizationService.loadUserDetails(createRequestAuthentication(USER)); - final NiFiUser user = details.getNiFiUser(); - - Assert.assertEquals(USER, user.getIdentity()); - Assert.assertNull(user.getChain()); - } - - /** - * Tests the case when the proxy does not have ROLE_PROXY. - * - * @throws Exception ex - */ - @Test(expected = UntrustedProxyException.class) - public void testInvalidProxy() throws Exception { - authorizationService.loadUserDetails(createRequestAuthentication(USER, USER)); - } - - /** - * Ensures the authorization service correctly handles proxy not found by attempting to create an account request for the proxy. - * - * @throws Exception ex - */ - @Test(expected = UntrustedProxyException.class) - public void testProxyNotFound() throws Exception { - try { - authorizationService.loadUserDetails(createRequestAuthentication(USER, PROXY_NOT_FOUND)); - } finally { - Mockito.verify(userService).createPendingUserAccount(Mockito.eq(PROXY_NOT_FOUND), Mockito.anyString()); - } - } - - /** - * Tests the case when there is a proxy. - * - * @throws Exception ex - */ - @Test - public void testProxy() throws Exception { - final NiFiUserDetails details = (NiFiUserDetails) authorizationService.loadUserDetails(createRequestAuthentication(USER, PROXY)); - final NiFiUser user = details.getNiFiUser(); - - // verify the user - Assert.assertEquals(USER, user.getIdentity()); - Assert.assertNotNull(user.getChain()); - - // get the proxy - final NiFiUser proxy = user.getChain(); - - // verify the proxy - Assert.assertEquals(PROXY, proxy.getIdentity()); - Assert.assertNull(proxy.getChain()); - } - - /** - * Tests the case when there is are multiple proxies. - * - * @throws Exception ex - */ - @Test - public void testProxyProxy() throws Exception { - final NiFiUserDetails details = (NiFiUserDetails) authorizationService.loadUserDetails(createRequestAuthentication(USER, PROXY, PROXY_PROXY)); - final NiFiUser user = details.getNiFiUser(); - - // verify the user - Assert.assertEquals(USER, user.getIdentity()); - Assert.assertNotNull(user.getChain()); - - // get the proxy - NiFiUser proxy = user.getChain(); - - // verify the proxy - Assert.assertEquals(PROXY, proxy.getIdentity()); - Assert.assertNotNull(proxy.getChain()); - - // get the proxies proxy - proxy = proxy.getChain(); - - // verify the proxies proxy - Assert.assertEquals(PROXY_PROXY, proxy.getIdentity()); - Assert.assertNull(proxy.getChain()); - } -} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/jwt/JwtServiceTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/jwt/JwtServiceTest.java index 658f3e6b88..59c66eff9a 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/jwt/JwtServiceTest.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/jwt/JwtServiceTest.java @@ -20,7 +20,7 @@ import io.jsonwebtoken.JwtException; import org.apache.commons.codec.CharEncoding; import org.apache.commons.codec.binary.Base64; import org.apache.nifi.admin.service.AdministrationException; -import org.apache.nifi.admin.service.UserService; +import org.apache.nifi.admin.service.KeyService; import org.apache.nifi.key.Key; import org.apache.nifi.web.security.token.LoginAuthenticationToken; import org.codehaus.jettison.json.JSONObject; @@ -131,7 +131,7 @@ public class JwtServiceTest { private static final String HMAC_SECRET = "test_hmac_shared_secret"; - private UserService mockUserService; + private KeyService mockKeyService; // Class under test private JwtService jwtService; @@ -177,10 +177,10 @@ public class JwtServiceTest { key.setIdentity(DEFAULT_IDENTITY); key.setKey(HMAC_SECRET); - mockUserService = Mockito.mock(UserService.class); - when(mockUserService.getKey(anyInt())).thenReturn(key); - when(mockUserService.getOrCreateKey(anyString())).thenReturn(key); - jwtService = new JwtService(mockUserService); + mockKeyService = Mockito.mock(KeyService.class); + when(mockKeyService.getKey(anyInt())).thenReturn(key); + when(mockKeyService.getOrCreateKey(anyString())).thenReturn(key); + jwtService = new JwtService(mockKeyService); } @After @@ -431,7 +431,7 @@ public class JwtServiceTest { logger.debug("Generating token for " + loginAuthenticationToken); // Set up the bad key service - UserService missingKeyService = Mockito.mock(UserService.class); + KeyService missingKeyService = Mockito.mock(KeyService.class); when(missingKeyService.getOrCreateKey(anyString())).thenThrow(new AdministrationException("Could not find a " + "key for that user")); jwtService = new JwtService(missingKeyService); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/otp/OtpAuthenticationFilterTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/otp/OtpAuthenticationFilterTest.java index ad6f7221d6..791ca54b04 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/otp/OtpAuthenticationFilterTest.java +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/otp/OtpAuthenticationFilterTest.java @@ -16,24 +16,17 @@ */ package org.apache.nifi.web.security.otp; -import org.apache.nifi.web.security.token.NiFiAuthorizationRequestToken; import org.junit.Before; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import javax.servlet.http.HttpServletRequest; -import java.util.List; import java.util.UUID; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doAnswer; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class OtpAuthenticationFilterTest { @@ -44,41 +37,11 @@ public class OtpAuthenticationFilterTest { private final static String DOWNLOAD_AUTHENTICATED_USER = "download-token-authenticated-user"; private final static String DOWNLOAD_TOKEN = "download-token"; - private OtpService otpService; private OtpAuthenticationFilter otpAuthenticationFilter; @Before public void setUp() throws Exception { - otpService = mock(OtpService.class); - doAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String downloadToken = (String) args[0]; - - if (DOWNLOAD_TOKEN.equals(downloadToken)) { - return DOWNLOAD_AUTHENTICATED_USER; - } - - throw new OtpAuthenticationException("Invalid token"); - } - }).when(otpService).getAuthenticationFromDownloadToken(anyString()); - doAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - String uiExtensionToken = (String) args[0]; - - if (UI_EXTENSION_TOKEN.equals(uiExtensionToken)) { - return UI_EXTENSION_AUTHENTICATED_USER; - } - - throw new OtpAuthenticationException("Invalid token"); - } - }).when(otpService).getAuthenticationFromUiExtensionToken(anyString()); - otpAuthenticationFilter = new OtpAuthenticationFilter(); - otpAuthenticationFilter.setOtpService(otpService); } @Test @@ -114,13 +77,9 @@ public class OtpAuthenticationFilterTest { when(request.getParameter(OtpAuthenticationFilter.ACCESS_TOKEN)).thenReturn(UI_EXTENSION_TOKEN); when(request.getContextPath()).thenReturn("/nifi-update-attribute-ui"); - final NiFiAuthorizationRequestToken result = otpAuthenticationFilter.attemptAuthentication(request); - final List chain = result.getChain(); - assertEquals(1, chain.size()); - assertEquals(UI_EXTENSION_AUTHENTICATED_USER, chain.get(0)); - - verify(otpService, times(1)).getAuthenticationFromUiExtensionToken(UI_EXTENSION_TOKEN); - verify(otpService, never()).getAuthenticationFromDownloadToken(anyString()); + final OtpAuthenticationRequestToken result = (OtpAuthenticationRequestToken) otpAuthenticationFilter.attemptAuthentication(request); + assertEquals(UI_EXTENSION_TOKEN, result.getToken()); + assertFalse(result.isDownloadToken()); } @Test @@ -131,13 +90,9 @@ public class OtpAuthenticationFilterTest { when(request.getContextPath()).thenReturn("/nifi-api"); when(request.getPathInfo()).thenReturn("/controller/provenance/events/0/content/input"); - final NiFiAuthorizationRequestToken result = otpAuthenticationFilter.attemptAuthentication(request); - final List chain = result.getChain(); - assertEquals(1, chain.size()); - assertEquals(DOWNLOAD_AUTHENTICATED_USER, chain.get(0)); - - verify(otpService, never()).getAuthenticationFromUiExtensionToken(anyString()); - verify(otpService, times(1)).getAuthenticationFromDownloadToken(DOWNLOAD_TOKEN); + final OtpAuthenticationRequestToken result = (OtpAuthenticationRequestToken) otpAuthenticationFilter.attemptAuthentication(request); + assertEquals(DOWNLOAD_TOKEN, result.getToken()); + assertTrue(result.isDownloadToken()); } @Test @@ -148,13 +103,9 @@ public class OtpAuthenticationFilterTest { when(request.getContextPath()).thenReturn("/nifi-api"); when(request.getPathInfo()).thenReturn("/controller/provenance/events/0/content/output"); - final NiFiAuthorizationRequestToken result = otpAuthenticationFilter.attemptAuthentication(request); - final List chain = result.getChain(); - assertEquals(1, chain.size()); - assertEquals(DOWNLOAD_AUTHENTICATED_USER, chain.get(0)); - - verify(otpService, never()).getAuthenticationFromUiExtensionToken(anyString()); - verify(otpService, times(1)).getAuthenticationFromDownloadToken(DOWNLOAD_TOKEN); + final OtpAuthenticationRequestToken result = (OtpAuthenticationRequestToken) otpAuthenticationFilter.attemptAuthentication(request); + assertEquals(DOWNLOAD_TOKEN, result.getToken()); + assertTrue(result.isDownloadToken()); } @Test @@ -167,13 +118,9 @@ public class OtpAuthenticationFilterTest { when(request.getContextPath()).thenReturn("/nifi-api"); when(request.getPathInfo()).thenReturn(String.format("/controller/process-groups/root/connections/%s/flowfiles/%s/content", uuid, uuid)); - final NiFiAuthorizationRequestToken result = otpAuthenticationFilter.attemptAuthentication(request); - final List chain = result.getChain(); - assertEquals(1, chain.size()); - assertEquals(DOWNLOAD_AUTHENTICATED_USER, chain.get(0)); - - verify(otpService, never()).getAuthenticationFromUiExtensionToken(anyString()); - verify(otpService, times(1)).getAuthenticationFromDownloadToken(DOWNLOAD_TOKEN); + final OtpAuthenticationRequestToken result = (OtpAuthenticationRequestToken) otpAuthenticationFilter.attemptAuthentication(request); + assertEquals(DOWNLOAD_TOKEN, result.getToken()); + assertTrue(result.isDownloadToken()); } @Test @@ -186,13 +133,9 @@ public class OtpAuthenticationFilterTest { when(request.getContextPath()).thenReturn("/nifi-api"); when(request.getPathInfo()).thenReturn(String.format("/controller/templates/%s", uuid)); - final NiFiAuthorizationRequestToken result = otpAuthenticationFilter.attemptAuthentication(request); - final List chain = result.getChain(); - assertEquals(1, chain.size()); - assertEquals(DOWNLOAD_AUTHENTICATED_USER, chain.get(0)); - - verify(otpService, never()).getAuthenticationFromUiExtensionToken(anyString()); - verify(otpService, times(1)).getAuthenticationFromDownloadToken(DOWNLOAD_TOKEN); + final OtpAuthenticationRequestToken result = (OtpAuthenticationRequestToken) otpAuthenticationFilter.attemptAuthentication(request); + assertEquals(DOWNLOAD_TOKEN, result.getToken()); + assertTrue(result.isDownloadToken()); } } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/otp/OtpAuthenticationProviderTest.java b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/otp/OtpAuthenticationProviderTest.java new file mode 100644 index 0000000000..a95c1a0626 --- /dev/null +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-security/src/test/java/org/apache/nifi/web/security/otp/OtpAuthenticationProviderTest.java @@ -0,0 +1,102 @@ +/* + * 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. + */ +package org.apache.nifi.web.security.otp; + +import org.apache.nifi.web.security.token.NiFiAuthenticationToken; +import org.apache.nifi.web.security.user.NiFiUserDetails; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +public class OtpAuthenticationProviderTest { + + private final static String UI_EXTENSION_AUTHENTICATED_USER = "ui-extension-token-authenticated-user"; + private final static String UI_EXTENSION_TOKEN = "ui-extension-token"; + + private final static String DOWNLOAD_AUTHENTICATED_USER = "download-token-authenticated-user"; + private final static String DOWNLOAD_TOKEN = "download-token"; + + private OtpService otpService; + private OtpAuthenticationProvider otpAuthenticationProvider; + + @Before + public void setUp() throws Exception { + otpService = mock(OtpService.class); + doAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + String downloadToken = (String) args[0]; + + if (DOWNLOAD_TOKEN.equals(downloadToken)) { + return DOWNLOAD_AUTHENTICATED_USER; + } + + throw new OtpAuthenticationException("Invalid token"); + } + }).when(otpService).getAuthenticationFromDownloadToken(anyString()); + doAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + String uiExtensionToken = (String) args[0]; + + if (UI_EXTENSION_TOKEN.equals(uiExtensionToken)) { + return UI_EXTENSION_AUTHENTICATED_USER; + } + + throw new OtpAuthenticationException("Invalid token"); + } + }).when(otpService).getAuthenticationFromUiExtensionToken(anyString()); + + otpAuthenticationProvider = new OtpAuthenticationProvider(otpService); + } + + @Test + public void testUiExtensionPath() throws Exception { + final OtpAuthenticationRequestToken request = new OtpAuthenticationRequestToken(UI_EXTENSION_TOKEN, false); + + final NiFiAuthenticationToken result = (NiFiAuthenticationToken) otpAuthenticationProvider.authenticate(request); + final NiFiUserDetails details = (NiFiUserDetails) result.getPrincipal(); + assertEquals(UI_EXTENSION_AUTHENTICATED_USER, details.getUsername()); + + verify(otpService, times(1)).getAuthenticationFromUiExtensionToken(UI_EXTENSION_TOKEN); + verify(otpService, never()).getAuthenticationFromDownloadToken(anyString()); + } + + @Test + public void testDownload() throws Exception { + final OtpAuthenticationRequestToken request = new OtpAuthenticationRequestToken(DOWNLOAD_TOKEN, true); + + final NiFiAuthenticationToken result = (NiFiAuthenticationToken) otpAuthenticationProvider.authenticate(request); + final NiFiUserDetails details = (NiFiUserDetails) result.getPrincipal(); + assertEquals(DOWNLOAD_AUTHENTICATED_USER, details.getUsername()); + + verify(otpService, never()).getAuthenticationFromUiExtensionToken(anyString()); + verify(otpService, times(1)).getAuthenticationFromDownloadToken(DOWNLOAD_TOKEN); + } + +} diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/pom.xml b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/pom.xml index 3d9a7d7bc7..c798191142 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/pom.xml +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/pom.xml @@ -32,7 +32,6 @@ counters.properties cluster.properties templates.properties - users.properties bulletin-board.properties login.properties provenance.properties @@ -55,7 +54,6 @@ src/main/resources/filters/${counters.filter} src/main/resources/filters/${cluster.filter} src/main/resources/filters/${templates.filter} - src/main/resources/filters/${users.filter} src/main/resources/filters/${bulletin.board.filter} src/main/resources/filters/${login.filter} src/main/resources/filters/${provenance.filter} @@ -93,7 +91,6 @@ **/counters.jsp, **/cluster.jsp, **/templates.jsp, - **/users.jsp, **/bulletin-board.jsp, **/login.jsp @@ -191,14 +188,6 @@ true - - src/main/webapp/WEB-INF/pages - WEB-INF/pages - - users.jsp - - true - src/main/webapp/WEB-INF/pages WEB-INF/pages @@ -241,7 +230,6 @@ counters-min.properties cluster-min.properties templates-min.properties - users-min.properties bulletin-board-min.properties login-min.properties provenance-min.properties @@ -297,8 +285,6 @@ ${staging.dir}/js/nf/canvas/nf-remote-process-group-ports.js ${staging.dir}/js/nf/canvas/nf-port-configuration.js ${staging.dir}/js/nf/canvas/nf-port-details.js - ${staging.dir}/js/nf/canvas/nf-secure-port-configuration.js - ${staging.dir}/js/nf/canvas/nf-secure-port-details.js ${staging.dir}/js/nf/canvas/nf-label-configuration.js ${staging.dir}/js/nf/canvas/nf-connection-configuration.js ${staging.dir}/js/nf/nf-connection-details.js @@ -422,20 +408,6 @@ ${staging.dir}/js/nf/cluster/nf-cluster-table.js - - true - ${project.build.directory}/${project.build.finalName}/js/nf/users/nf-users-all.js - - ${staging.dir}/js/nf/nf-client.js - ${staging.dir}/js/nf/nf-common.js - ${staging.dir}/js/nf/nf-universal-capture.js - ${staging.dir}/js/nf/nf-dialog.js - ${staging.dir}/js/nf/nf-storage.js - ${staging.dir}/js/nf/nf-ajax-setup.js - ${staging.dir}/js/nf/users/nf-users.js - ${staging.dir}/js/nf/users/nf-users-table.js - - true ${project.build.directory}/${project.build.finalName}/js/nf/bulletin-board/nf-bulletin-board-all.js @@ -559,16 +531,6 @@ ${staging.dir}/css/templates.css - - true - ${project.build.directory}/${project.build.finalName}/css/nf-users-all.css - - ${staging.dir}/css/main.css - ${staging.dir}/css/banner.css - ${staging.dir}/css/dialog.css - ${staging.dir}/css/users.css - - true ${project.build.directory}/${project.build.finalName}/css/nf-bulletin-board-all.css @@ -624,8 +586,6 @@ css/nf-cluster-all.css.gz, css/nf-templates-all.css, css/nf-templates-all.css.gz, - css/nf-users-all.css, - css/nf-users-all.css.gz, css/nf-bulletin-board-all.css, css/nf-bulletin-board-all.css.gz, css/nf-login-all.css, @@ -665,8 +625,6 @@ js/nf/cluster/nf-cluster-all.js.gz, js/nf/templates/nf-templates-all.js, js/nf/templates/nf-templates-all.js.gz, - js/nf/users/nf-users-all.js, - js/nf/users/nf-users-all.js.gz, js/nf/bulletin-board/nf-bulletin-board-all.js, js/nf/bulletin-board/nf-bulletin-board-all.js.gz, js/nf/login/nf-login-all.js, diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/canvas.properties b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/canvas.properties index ab42f863c6..67a02f4f13 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/canvas.properties +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/canvas.properties @@ -38,8 +38,6 @@ nf.canvas.script.tags=\n\ \n\ \n\ -\n\ -\n\ \n\ \n\ \n\ diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/users-min.properties b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/users-min.properties deleted file mode 100644 index 9375334eab..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/users-min.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. - -nf.users.script.tags= -nf.users.style.tags=\n\ - \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/users.properties b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/users.properties deleted file mode 100644 index 0b3736360a..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/resources/filters/users.properties +++ /dev/null @@ -1,29 +0,0 @@ -# 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. - -nf.users.script.tags=\n\ -\n\ -\n\ -\n\ -\n\ -\n\ -\n\ - -nf.users.style.tags=\n\ -\n\ -\n\ -\n\ -\n\ - \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/pages/canvas.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/pages/canvas.jsp index c6fe35de6b..fbab590a5c 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/pages/canvas.jsp +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/pages/canvas.jsp @@ -124,8 +124,6 @@ - - diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/pages/users.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/pages/users.jsp deleted file mode 100644 index b3e09681da..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/pages/users.jsp +++ /dev/null @@ -1,72 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> - - - - NiFi Users - - - - ${nf.users.style.tags} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${nf.users.script.tags} - - - - - - - - - - - - - - -
-
- - diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/canvas-header.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/canvas-header.jsp index 7a1d22d642..ed93e43d30 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/canvas-header.jsp +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/canvas-header.jsp @@ -33,7 +33,6 @@ - diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/secure-port-configuration.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/secure-port-configuration.jsp deleted file mode 100644 index bd870188f6..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/secure-port-configuration.jsp +++ /dev/null @@ -1,82 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> -
-
- -
-
-
-
-
Port name
-
- -
-
- Enabled -
-
-
-
-
-
- Id -
-
- -
-
-
-
- Concurrent tasks - Info -
-
- -
-
-
-
Comments
-
- -
-
-
-
-
-
Search Users
-
- -
-
-
-
Allowed Users
-
-
    -
    -
    -
    -
    Allowed Groups
    -
    -
      -
      -
      -
      -
      -
      -
      -
      \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/secure-port-details.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/secure-port-details.jsp deleted file mode 100644 index 7b62450166..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/canvas/secure-port-details.jsp +++ /dev/null @@ -1,67 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> -
      -
      -
      -
      -
      -
      -
      Port name
      -
      -
      -
      -
      -
      -
      Id
      -
      - -
      -
      -
      -
      - Concurrent tasks - Info -
      -
      -
      -
      -
      -
      -
      Comments
      -
      -
      -
      -
      -
      -
      -
      -
      Allowed Users
      -
      -
        -
        -
        -
        -
        Allowed Groups
        -
        -
          -
          -
          -
          -
          -
          -
          \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/group-revoke-dialog.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/group-revoke-dialog.jsp deleted file mode 100644 index 436e28dd85..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/group-revoke-dialog.jsp +++ /dev/null @@ -1,22 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> -
          -
          - Are you sure you want to revoke access for all users in ''? -
          -
          diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/group-roles-dialog.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/group-roles-dialog.jsp deleted file mode 100644 index f0db9580c1..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/group-roles-dialog.jsp +++ /dev/null @@ -1,52 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> -
          -
          -
          -
          Group
          -
          - -
          -
          -
          -
          -
          Roles
          -
          -
          -
          Administrator
          -
          -
          -
          Data Flow Manager
          -
          -
          -
          Read Only
          -
          -
          -
          Provenance
          -
          -
          -
          NiFi
          -
          -
          -
          Proxy
          -
          -
          -
          -
          -
          -
          diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-delete-dialog.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-delete-dialog.jsp deleted file mode 100644 index d926691585..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-delete-dialog.jsp +++ /dev/null @@ -1,23 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> -
          -
          - - Are you sure you want to delete the user account for ''? -
          -
          diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-details-dialog.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-details-dialog.jsp deleted file mode 100644 index 8a818825d4..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-details-dialog.jsp +++ /dev/null @@ -1,56 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> -
          -
          -
          -
          User
          -
          - -
          -
          -
          -
          -
          Identity
          -
          - -
          -
          -
          -
          -
          Created
          -
          - -
          -
          -
          -
          -
          Last Verified
          -
          - -
          -
          -
          -
          -
          Justification
          -
          -
          -
          -
          -
          -
          -
          diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-group-dialog.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-group-dialog.jsp deleted file mode 100644 index 05788253f5..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-group-dialog.jsp +++ /dev/null @@ -1,27 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> -
          -
          -
          -
          Group name
          -
          - -
          -
          -
          -
          diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-revoke-dialog.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-revoke-dialog.jsp deleted file mode 100644 index 498c3c2dcb..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-revoke-dialog.jsp +++ /dev/null @@ -1,23 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> -
          -
          - - Are you sure you want to revoke access for ''? -
          -
          diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-roles-dialog.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-roles-dialog.jsp deleted file mode 100644 index dfd256b063..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/user-roles-dialog.jsp +++ /dev/null @@ -1,60 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> -
          -
          -
          - -
          User
          -
          - -
          -
          -
          -
          -
          Justification
          -
          -
          -
          -
          -
          -
          -
          Roles
          -
          -
          -
          Administrator
          -
          -
          -
          Data Flow Manager
          -
          -
          -
          Read Only
          -
          -
          -
          Provenance
          -
          -
          -
          NiFi
          -
          -
          -
          Proxy
          -
          -
          -
          -
          -
          -
          diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/users-content.jsp b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/users-content.jsp deleted file mode 100644 index cdaf6c1bcf..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/WEB-INF/partials/users/users-content.jsp +++ /dev/null @@ -1,46 +0,0 @@ -<%-- - 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. ---%> -<%@ page contentType="text/html" pageEncoding="UTF-8" session="false" %> -
          -
          -
          NiFi Users
          -
          -
          - -
          -
          -
          - Displaying  of  -
          -
          -
          -
          -
          -
          - Last updated:  -
          -
          -
          -
          -
          -  Show by group -
          -
          Group
          -
          -
          -
          -
          \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/header.css b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/header.css index 200f6bb705..0dd10d7ce6 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/header.css +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/header.css @@ -622,19 +622,6 @@ div.provenance-link-disabled { background: transparent url(../images/iconProvenance.png) no-repeat scroll top right; } -div.users-link { - background: transparent url(../images/iconAdminUser.png) no-repeat scroll top left; -} - -div.users-link-hover { - background: transparent url(../images/iconAdminUser.png) no-repeat scroll top center; - cursor: pointer; -} - -div.users-link-disabled { - background: transparent url(../images/iconAdminUser.png) no-repeat scroll top right; -} - div.cluster-link { background: transparent url(../images/iconCluster.png) no-repeat scroll top left; } diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/port-configuration.css b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/port-configuration.css index ce1f00a768..f48d893863 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/port-configuration.css +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/port-configuration.css @@ -54,137 +54,4 @@ div.port-enabled-container { float: left; margin-top: 5px; margin-left: 10px; -} - -/* - Secure port configuration -*/ - -#secure-port-configuration { - z-index: 1301; - display: none; - width: 400px; - height: 450px; -} - -#secure-port-configuration div.dialog-content { - margin-top: -10px; -} -#secure-port-configuration-tabs { - background-color: transparent; - border-bottom: 3px solid #666666; - height: 21px; - width: 380px; -} - -#secure-port-configuration div.configuration-tab { - z-index: 1301; - display: none; - background: url("../images/bgTabContainer.png") repeat-x scroll 0 0 #EEEEEE; - padding: 10px; - width: 360px; - height: 340px; -} - -#secure-port-name { - width: 280px; - float: left; -} - -.secure-port-field { - width: 350px; -} - -textarea.secure-port-field { - height: 100px; -} - -div.secure-port-setting { - margin-bottom: 15px; - width: 360px; -} - -input.search-users { - color: #888; -} - -#search-users-results .ui-autocomplete { - max-height: 300px; - overflow: auto; - border: 1px solid #aaaaaa; - z-index: 1351; - border-radius: 0; -} - -#search-users-results .ui-menu .ui-menu-item a.ui-state-focus { - background: #D4E0E5 !important; - border: 1px solid #999999; - border-radius: 0; -} - -li.search-users-header { - font-weight: bold; - padding-top: 4px; - padding-left: 4px; - padding-right: 4px; - height: 14px; -} - -div.search-users-match-header { - font-weight: normal; - margin-left: 10px; -} - -li.search-users-no-matches { - padding: 4px; - font-weight: bold; - color: #aaa; - font-style: italic; -} - -#secure-port-configuration div.port-setting-left { - margin-right: 10px; -} - -#secure-port-configuration div.port-setting-left, #secure-port-configuration div.port-setting-right { - width: 185px; - float: left; -} - -div.allowed-container { - width: 358px; - height: 100px; - border: 1px solid #aaa; - overflow-x: hidden; - overflow-y: scroll; -} - -ul.allowed { - list-style-type: none; -} - -ul.allowed li { - height: 16px; - width: 331px; - border: 1px solid #618BA3; - background-color: #c5d5de; - color: #555; - overflow: hidden; - margin: 2px; - padding: 2px; - line-height: 16px; - font-weight: bold; -} - -span.allowed-entity { - float: left; - width: 310px; -} - -div.remove-allowed-entity { - float: right; - width: 16px; - height: 16px; - background-image: url(../images/iconDelete.png); - cursor: pointer; } \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/port-details.css b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/port-details.css index 831c5ee5be..055103e3de 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/port-details.css +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/port-details.css @@ -23,31 +23,4 @@ display: none; width: 400px; height: 300px; -} - -/* - Secure port details. -*/ - -#secure-port-details { - z-index: 1301; - display: none; - height: 425px; - width: 400px; -} - -#secure-port-details-tabs { - background-color: transparent; - border-bottom: 3px solid #666666; - height: 21px; - width: 380px; -} - -#secure-port-details div.configuration-tab { - background: url("../images/bgTabContainer.png") repeat-x scroll 0 0 #EEEEEE; - display: none; - height: 315px; - padding: 10px; - width: 360px; - z-index: 1301; } \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/users.css b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/users.css deleted file mode 100644 index 9c304fecfe..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/css/users.css +++ /dev/null @@ -1,254 +0,0 @@ -/* - * 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. - */ -/* - Counters Styles -*/ - -#users { - position: absolute; - top: 0px; - bottom: 0px; - left: 0px; - right: 0px; -} - -#users-header-and-filter { - height: 35px; - margin-top: 20px; - margin-left: 20px; - margin-right: 20px; -} - -#users-header-text { - float: left; - font-size: 16px; - font-weight: bold; -} - -#users-refresh-container { - height: 26px; - margin-left: 20px; - margin-right: 20px; - margin-top: 18px; - -webkit-user-select: none; - -moz-user-select: none; -} - -#users-last-refreshed-container { - float: left; - color: #666; - font-weight: normal; - margin-top: 6px; - margin-left: 3px; -} - -#users-loading-container { - float: left; - width: 16px; - height: 16px; - background-color: transparent; - margin-top: 4px; - margin-left: 3px; -} - -#users-last-refreshed { - font-weight: bold; -} - -#users-header { - padding-top: 10px; -} - -#refresh-button { - height: 24px; - width: 26px; - float: left; -} - -/* group controls */ - -#group-controls-container { - position: absolute; - right: 20px; - top: 75px; -} - -#group-collaspe-container { - float: left; - margin-top: 5px; - margin-right: 10px; -} - -#group-button { - height: 20px; - line-height: 20px; - width: 55px; - text-align: center; - font-weight: bold; - border: 1px solid #AAAAAA; - color: #525252; - float: left; -} - -/* group dialog */ - -#user-group-dialog { - display: none; - width: 350px; - height: 150px; - z-index: 1301; -} - -#group-name { - width: 320px; -} - -/* filter controls */ - -#users-filter-controls { - float: right; -} - -#users-filter-container { - height: 24px; - width: 318px; -} - -#users-filter { - padding: 3px 0px 1px 3px; - font-size: 12px; - height: 18px; - line-height: 20px; - width: 173px; - border: 1px solid #ccc; - margin-right: 3px; - float: left; -} - -input.users-filter-list { - color: #888; -} - -#users-filter-type { - width: 127px; - height: 18px; - line-height: 18px; - float: left; -} - -#users-filter-stats { - font-size: 9px; - font-weight: bold; - color: #9f6000; - clear: left; - line-height: normal; - margin-left: 5px; -} - -/* users table */ - -#users-table { - position: absolute; - top: 100px; - left: 20px; - bottom: 20px; - right: 20px; - border: 1px solid #666; - overflow: hidden; -} - -a.user-account-action:link, a.user-account-action:visited, a.user-account-action:active { - color: #355b6a; - text-decoration: underline; -} - -a.user-account-action:hover { - color: #4b788a; - text-decoration: none; -} - -/* user details dialog */ - -#user-details-dialog { - display: none; - width: 350px; - height: 400px; - z-index: 1301; -} - -#user-justification-details-dialog { - max-height: 120px; - overflow-y: auto; -} - -#user-roles-dialog { - display: none; - width: 350px; - height: 400px; - z-index: 1301; -} - -#user-justification-roles-dialog { - max-height: 120px; - overflow-y: auto; -} - -#group-roles-dialog { - display: none; - width: 350px; - height: 375px; - z-index: 1301; -} - -div.roles-container { - margin-top: 3px; - margin-left: 3px; -} - -div.role-container { - height: 16px; -} - -div.role-name { - display: inline-block; - line-height: normal; -} - -/* user revoke dialog */ - -#user-revoke-dialog { - display: none; - width: 450px; - height: 165px; - z-index: 1301; -} - -#group-revoke-dialog { - display: none; - width: 450px; - height: 165px; - z-index: 1301; -} - -/* user delete dialog */ - -#user-delete-dialog { - display: none; - width: 450px; - height: 165px; - z-index: 1301; -} \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/images/iconAdminUser.png b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/images/iconAdminUser.png deleted file mode 100755 index fbaf73bfb6e03cd080685014bf6c0228592e5ef5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1960 zcmV;Z2UqxsP)7IZ~ebVG7wVRUJ4ZXi@?ZDjy3H7_tTFEKGNOlJN700#g` zL_t(oh3%PJY#dh^$Nw{DX7=XG+FlbUc5F9xLa;!Ms!$q4AT&iN6%Q>u@m3+CJhkdm z5fpJ1Jn>c}NRbPIePK*JmWTjE@wP3TNC&QWC)pBUb|DW{fk?RTX8% zKgO9ZH{SVROH(FSB}-EKisd!jzpquP%c*4?G$K`x7w4uiGw}gDMxm%0_8&fq-TMwU zJdn+#k%z~NbMqT;9@`eqnsiVuWRXk9AvlLj2)gzRprs?$)ctC%ajGmql_hvq33tXu z;V}vT@EEO}Tcv8BN0BO5!n0@%4z2ci6cI@Rkt7I4v67gB;2Z!TIIo;DTJ6(_>Q-FI z-gqu~b{QlRL9viS+U2(LF{g-0Q2DqPz}i3_}W?q4TcTOuQpOlV?h`Snn1bm`>Rj#W7||3{5T z(1?UsclWwBMO6_D29eJsk&90w8X|b^`LCZo&=Yxiq=UWk%kRGM7J!k%y;7)NLK>+= zth;j)P6oO7G$J8_XCH8e*Km%HMC)=^t0^1~uWOSDfubm|%LXic1wlo|$WZ_3o>ua5 zU&MQ5Kwf#vSV@nZdH4M)r}k7O5>z4~915a$a327`_kFmoi(P$#aI7-Y_h;~xqfa4h z#^HSUYZPysg?;Y=o)~O9@{3bXzXqVEUP7u=iEsd$a=!4?lYkkAc);QJF5pv5aAdg> zs;ZzZ+EL*E@Hj_HTNECnDCs#24eW)=ba;sgxQln-W#`b>h9iUW(rb1}uX5^EoJJ%J zJ~j+WDNNIZX`1NhiowWd(HbDoBnHGU!{Z!hFI-Ff`LCDesgc2<9{C7>UG);u*2HEU zfUo1A3C?Q85lKR{qYIpKFiOEFMKBzOYnuoV8ARfM9*6J+?%dBLKAKC-bJs*~$T{L# zr7EZH8aMvo70lkdi)1nh#u!vBfRCmo5$)*2XFfRu*f{_`RG%UU%4N^-nXwF3&H+H6 z5#s=0eCpQb9KN0-n&7Oiap`0Nxoj4OVSoz(LI{=@(+Gw_*cIypm<_-O@i`QUb4hTY zyCwv+Ah=iM)HKd27VwAP{}$;~3Y1bX#=sbZX_^@O;1V3Gj3(6Z z*P!MZphjjjp}Lzv%k>)Kz$pQbz+sMqf8M--l3{>z4lV@5gQ`m|#NjcDzNfzg-*X|D z3r;Nz$J9Y01h`v-L>geD9hEy^MN+~F%a9y_&jswdyaO#C`;=u3_ic{~P zoL@wM77#@ds+$EhG8ms(9s`i6mrx^|y~9HgQ}00J7olyDGym_IN|kY53D1MaIXuq; zqb?2~`ZT&aJK-!%gW4r1+(r;C2)Dpp6UmY^76`XiIW;RTv9M50rW&q`a7e=szxNXy z9Oy=A>}QwpB7miO3Dx8D4|IcX1E*LlJ~VBOd8$fq z?2BJUtUUsnn1roo;Cn6<-}PkfD1ur@nd;bL^s_IvwMMHPsm2>%-F4meK;YrhAvlMg z&mtJqfZQz1iQl2LoWx|pM(DsZ&X2zTof7~A0E$WlG_sG|@L82p2Sn3=!YpV5oO=7X z>$3@62+^*PhmR?~@58YzC<+0rJZSm`sA(Ww^q|D{Irnqc2?>&r2%&*+Yv#ZAakY$F zr^CHcZ1iS&JY1gd*Z*-wF61+C%LVr1KizsMYx47D%Slb7e9_R&Hqr5sXl(RmdK~5X zep-VwdRu>F&ackC7khlTe>}kSerI7)c5D+KbJ&y~eW_*l(D_h%XX;yD{d`SM&8fP9 z_OMGok9n|U$5_VY>oc=g?=8QPx5brkC}6xlV?S~-YdLBS&bf)DZQ1g*nsnwYm3{)@qIxw;kF2B!E-HEkUCBWd-lH_j>Z!8Oaq!TF8$`aW3PT9%nwb? z=dR9Vy^EoMR@}x)t8)Ih0cX1^ZB@aR_Vmr=+^Zq(9V+nXRnoENq81Dn8!-)NZjB29 z=mro$<%MEyBIVOH?HgV 0) { // clear the state - var revision = nf.Client.getRevision(); + var revision = { + 'revision': nf.Client.getRevision() + }; + var component = componentStateTable.data('component'); $.ajax({ type: 'POST', url: component.uri + '/state/clear-requests', - data: { - version: revision.version, - clientId: revision.clientId - }, + data: JSON.stringify(revision), dataType: 'json' }).done(function (response) { // update the revision diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-connection-configuration.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-connection-configuration.js index 9f83fae31c..73ea71bbc0 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-connection-configuration.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-connection-configuration.js @@ -24,7 +24,7 @@ nf.ConnectionConfiguration = (function () { var config = { urls: { - controller: '../nifi-api/controller', + api: '../nifi-api', prioritizers: '../nifi-api/controller/prioritizers' } }; @@ -248,7 +248,7 @@ nf.ConnectionConfiguration = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(processGroupData.component.id), + url: config.urls.api + '/process-groups/' + encodeURIComponent(processGroupData.component.id), data: { verbose: true }, @@ -473,7 +473,7 @@ nf.ConnectionConfiguration = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(processGroupData.component.id), + url: config.urls.api + '/process-groups/' + encodeURIComponent(processGroupData.component.id), data: { verbose: true }, @@ -717,8 +717,14 @@ nf.ConnectionConfiguration = (function () { var xOffset = nf.Connection.config.selfLoopXOffset; var yOffset = nf.Connection.config.selfLoopYOffset; - bends.push((rightCenter.x + xOffset) + ',' + (rightCenter.y - yOffset)); - bends.push((rightCenter.x + xOffset) + ',' + (rightCenter.y + yOffset)); + bends.push({ + 'x': (rightCenter.x + xOffset), + 'y': (rightCenter.y - yOffset) + }); + bends.push({ + 'x': (rightCenter.x + xOffset), + 'y': (rightCenter.y + yOffset) + }); } else { var existingConnections = []; @@ -794,10 +800,16 @@ nf.ConnectionConfiguration = (function () { while (positioned === false) { // consider above and below, then increment and try again (if necessary) if (collides(xCandidate - xStep, yCandidate - yStep) === false) { - bends.push((xCandidate - xStep) + ',' + (yCandidate - yStep)); + bends.push({ + 'x': (xCandidate - xStep), + 'y': (yCandidate - yStep) + }); positioned = true; } else if (collides(xCandidate + xStep, yCandidate + yStep) === false) { - bends.push((xCandidate + xStep) + ',' + (yCandidate + yStep)); + bends.push({ + 'x': (xCandidate + xStep), + 'y': (yCandidate + yStep) + }); positioned = true; } @@ -827,30 +839,36 @@ nf.ConnectionConfiguration = (function () { var prioritizers = $('#prioritizer-selected').sortable('toArray'); if (validateSettings()) { - var revision = nf.Client.getRevision(); + var connectionEntity = { + 'revision': nf.Client.getRevision(), + 'connection': { + 'name': connectionName, + 'source': { + 'id': sourceId, + 'groupId': sourceGroupId, + 'type': sourceType + }, + 'destination': { + 'id': destinationId, + 'groupId': destinationGroupId, + 'type': destinationType + }, + 'selectedRelationships': selectedRelationships, + 'flowFileExpiration': flowFileExpiration, + 'backPressureDataSizeThreshold': backPressureDataSizeThreshold, + 'backPressureObjectThreshold': backPressureObjectThreshold, + 'bends': bends, + 'prioritizers': prioritizers + } + }; // create the new connection $.ajax({ type: 'POST', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(nf.Canvas.getGroupId()) + '/connections', - data: { - version: revision.version, - clientId: revision.clientId, - sourceId: sourceId, - sourceGroupId: sourceGroupId, - sourceType: sourceType, - relationships: selectedRelationships, - bends: bends, - name: connectionName, - flowFileExpiration: flowFileExpiration, - backPressureObjectThreshold: backPressureObjectThreshold, - backPressureDataSizeThreshold: backPressureDataSizeThreshold, - prioritizers: prioritizers, - destinationId: destinationId, - destinationGroupId: destinationGroupId, - destinationType: destinationType - }, - dataType: 'json' + url: config.urls.api + '/process-groups/' + encodeURIComponent(nf.Canvas.getGroupId()) + '/connections', + data: JSON.stringify(connectionEntity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { // update the revision nf.Client.setRevision(response.revision); @@ -882,6 +900,7 @@ nf.ConnectionConfiguration = (function () { */ var updateConnection = function (selectedRelationships) { // get the connection details + var connectionId = $('#connection-id').text(); var connectionUri = $('#connection-uri').val(); // get the source details @@ -904,26 +923,31 @@ nf.ConnectionConfiguration = (function () { var prioritizers = $('#prioritizer-selected').sortable('toArray'); if (validateSettings()) { - var revision = nf.Client.getRevision(); + var connectionEntity = { + 'revision': nf.Client.getRevision(), + 'connection': { + 'id': connectionId, + 'name': connectionName, + 'destination': { + 'id': destinationId, + 'groupId': destinationGroupId, + 'type': destinationType + }, + 'selectedRelationships': selectedRelationships, + 'flowFileExpiration': flowFileExpiration, + 'backPressureDataSizeThreshold': backPressureDataSizeThreshold, + 'backPressureObjectThreshold': backPressureObjectThreshold, + 'prioritizers': prioritizers + } + }; // update the connection return $.ajax({ type: 'PUT', url: connectionUri, - data: { - version: revision.version, - clientId: revision.clientId, - relationships: selectedRelationships, - name: connectionName, - flowFileExpiration: flowFileExpiration, - backPressureObjectThreshold: backPressureObjectThreshold, - backPressureDataSizeThreshold: backPressureDataSizeThreshold, - prioritizers: prioritizers, - destinationId: destinationId, - destinationType: destinationType, - destinationGroupId: destinationGroupId - }, - dataType: 'json' + data: JSON.stringify(connectionEntity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { if (nf.Common.isDefinedAndNotNull(response.connection)) { var connection = response.connection; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-connection.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-connection.js index ec0ed4fc3c..8cab85e71f 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-connection.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-connection.js @@ -1168,18 +1168,20 @@ nf.Connection = (function () { connection.call(updateConnections, true, false); }); } else { - var revision = nf.Client.getRevision(); - // get the destination details var destinationData = destination.datum(); var destinationType = nf.CanvasUtils.getConnectableTypeForDestination(destination); - var updatedConnectionData = { - version: revision.version, - clientId: revision.clientId, - destinationId: destinationData.component.id, - destinationType: destinationType, - destinationGroupId: nf.Canvas.getGroupId() + var connectionEntity = { + 'revision': nf.Client.getRevision(), + 'connection': { + 'id': connectionData.component.id, + 'destination': { + 'id': destinationData.component.id, + 'groupId': nf.Canvas.getGroupId(), + 'type': destinationType + } + } }; // if this is a self loop and there are less than 2 bends, add them @@ -1191,16 +1193,23 @@ nf.Connection = (function () { var xOffset = nf.Connection.config.selfLoopXOffset; var yOffset = nf.Connection.config.selfLoopYOffset; - updatedConnectionData.bends = []; - updatedConnectionData.bends.push((rightCenter.x + xOffset) + ',' + (rightCenter.y - yOffset)); - updatedConnectionData.bends.push((rightCenter.x + xOffset) + ',' + (rightCenter.y + yOffset)); + connectionEntity.connection.bends = []; + connectionEntity.connection.bends.push({ + 'x': (rightCenter.x + xOffset), + 'y': (rightCenter.y - yOffset) + }); + connectionEntity.connection.bends.push({ + 'x': (rightCenter.x + xOffset), + 'y': (rightCenter.y + yOffset) + }); } $.ajax({ type: 'PUT', url: connectionData.component.uri, - data: updatedConnectionData, - dataType: 'json' + data: JSON.stringify(connectionEntity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { var updatedConnectionData = response.connection; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-controller-service.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-controller-service.js index ebaf6c1260..2cf0fc0fa9 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-controller-service.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-controller-service.js @@ -548,7 +548,7 @@ nf.ControllerService = (function () { return $.ajax({ type: 'GET', - url: '../nifi-api/controller/bulletin-board', + url: '../nifi-api/bulletin-board', data: { sourceId: ids }, @@ -564,22 +564,26 @@ nf.ControllerService = (function () { * @param {function} pollCondition */ var setEnabled = function (controllerService, enabled, pollCondition) { - var revision = nf.Client.getRevision(); - + // build the request entity + var controllerServiceEntity = { + 'revision': nf.Client.getRevision(), + 'controllerService': { + 'id': controllerService.id, + 'state': enabled ? 'ENABLED' : 'DISABLED' + } + }; + var updated = $.ajax({ type: 'PUT', url: controllerService.uri, - data: { - clientId: revision.clientId, - version: revision.version, - state: enabled === true ? 'ENABLED' : 'DISABLED' - }, - dataType: 'json' + data: JSON.stringify(controllerServiceEntity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { nf.Client.setRevision(response.revision); }).fail(nf.Common.handleAjaxError); - // wait unil the polling of each service finished + // wait until the polling of each service finished return $.Deferred(function(deferred) { updated.done(function() { var serviceUpdated = pollService(controllerService, function (service, bulletins) { @@ -650,18 +654,19 @@ nf.ControllerService = (function () { * @param {function} pollCondition */ var updateReferencingSchedulableComponents = function (controllerService, running, pollCondition) { - var revision = nf.Client.getRevision(); - + var referenceEntity = { + 'revision': nf.Client.getRevision(), + 'id': controllerService.id, + 'state': running ? 'RUNNING' : 'STOPPED' + }; + // issue the request to update the referencing components var updated = $.ajax({ type: 'PUT', url: controllerService.uri + '/references', - data: { - clientId: revision.clientId, - version: revision.version, - state: running ? 'RUNNING' : 'STOPPED' - }, - dataType: 'json' + data: JSON.stringify(referenceEntity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { nf.Client.setRevision(response.revision); }).fail(nf.Common.handleAjaxError); @@ -908,18 +913,20 @@ nf.ControllerService = (function () { * @param {function} pollCondition */ var updateReferencingServices = function (controllerService, enabled, pollCondition) { - var revision = nf.Client.getRevision(); + // build the reference entity + var referenceEntity = { + 'revision': nf.Client.getRevision(), + 'id': controllerService.id, + 'state': enabled ? 'ENABLED' : 'DISABLED' + }; // issue the request to update the referencing components var updated = $.ajax({ type: 'PUT', url: controllerService.uri + '/references', - data: { - clientId: revision.clientId, - version: revision.version, - state: enabled ? 'ENABLED' : 'DISABLED' - }, - dataType: 'json' + data: JSON.stringify(referenceEntity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { nf.Client.setRevision(response.revision); }).fail(nf.Common.handleAjaxError); @@ -1301,7 +1308,6 @@ nf.ControllerService = (function () { data: JSON.stringify(updatedControllerService), url: controllerService.uri, dataType: 'json', - processData: false, contentType: 'application/json' }).done(function (response) { if (nf.Common.isDefinedAndNotNull(response.controllerService)) { @@ -1605,7 +1611,7 @@ nf.ControllerService = (function () { // get the controller service history var loadHistory = $.ajax({ type: 'GET', - url: '../nifi-api/controller/history/controller-services/' + encodeURIComponent(controllerService.id), + url: '../nifi-api/history/controller-services/' + encodeURIComponent(controllerService.id), dataType: 'json' }); @@ -1762,7 +1768,7 @@ nf.ControllerService = (function () { // get the controller service history var loadHistory = $.ajax({ type: 'GET', - url: '../nifi-api/controller/history/controller-services/' + encodeURIComponent(controllerService.id), + url: '../nifi-api/history/controller-services/' + encodeURIComponent(controllerService.id), dataType: 'json' }); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-draggable.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-draggable.js index d44f1ed9b1..d4dd1deb3b 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-draggable.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-draggable.js @@ -27,7 +27,6 @@ nf.Draggable = (function () { * @param {selection} dragSelection The current drag selection */ var updateComponentsPosition = function (dragSelection) { - var revision = nf.Client.getRevision(); var updates = d3.map(); // determine the drag delta @@ -44,8 +43,19 @@ nf.Draggable = (function () { var updateComponentPosition = function(d) { var newPosition = { - x: d.component.position.x + delta.x, - y: d.component.position.y + delta.y + 'x': d.component.position.x + delta.x, + 'y': d.component.position.y + delta.y + }; + + // build the entity + var entity = { + 'revision': nf.Client.getRevision() + }; + + // use bracket notation to dynamic get the key based on the entity type + entity[nf[d.type].getEntityKey(d)] = { + 'id': d.component.id, + 'position': newPosition }; // update the component positioning @@ -53,13 +63,9 @@ nf.Draggable = (function () { $.ajax({ type: 'PUT', url: d.component.uri, - data: { - version: revision.version, - clientId: revision.clientId, - x: newPosition.x, - y: newPosition.y - }, - dataType: 'json' + data: JSON.stringify(entity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { // update the revision nf.Client.setRevision(response.revision); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-funnel.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-funnel.js index 8943ddf294..555450e30d 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-funnel.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-funnel.js @@ -253,7 +253,14 @@ nf.Funnel = (function () { set(funnels); } }, - + + /** + * Returns the entity key when marshalling an entity of this type. + */ + getEntityKey: function (d) { + return 'funnel'; + }, + /** * Removes the specified funnel. * diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-go-to.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-go-to.js index 2c75b7ef1b..f3d0738c2c 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-go-to.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-go-to.js @@ -24,8 +24,8 @@ nf.GoTo = (function () { var config = { urls: { - controller: '../nifi-api/controller', - processGroups: '../nifi-api/controller/process-groups/' + api: '../nifi-api', + processGroups: '../nifi-api/process-groups/' } }; @@ -350,7 +350,7 @@ nf.GoTo = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', + url: config.urls.api + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', dataType: 'json' }).done(function (response) { var connections = response.connections; @@ -389,7 +389,7 @@ nf.GoTo = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', + url: config.urls.api + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', dataType: 'json' }).done(function (response) { var connections = response.connections; @@ -428,7 +428,7 @@ nf.GoTo = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', + url: config.urls.api + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', dataType: 'json' }).done(function (response) { var connections = response.connections; @@ -467,7 +467,7 @@ nf.GoTo = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', + url: config.urls.api + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', dataType: 'json' }).done(function (response) { var connections = response.connections; @@ -506,7 +506,7 @@ nf.GoTo = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', + url: config.urls.api + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', dataType: 'json' }).done(function (response) { var connections = response.connections; @@ -545,7 +545,7 @@ nf.GoTo = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(nf.Canvas.getParentGroupId()) + '/connections', + url: config.urls.api + '/process-groups/' + encodeURIComponent(nf.Canvas.getParentGroupId()) + '/connections', dataType: 'json' }).done(function (response) { var connections = response.connections; @@ -587,7 +587,7 @@ nf.GoTo = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(nf.Canvas.getParentGroupId()) + '/connections', + url: config.urls.api + '/process-groups/' + encodeURIComponent(nf.Canvas.getParentGroupId()) + '/connections', dataType: 'json' }).done(function (response) { var connections = response.connections; @@ -629,7 +629,7 @@ nf.GoTo = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', + url: config.urls.api + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', dataType: 'json' }).done(function (response) { var connections = response.connections; @@ -668,7 +668,7 @@ nf.GoTo = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', + url: config.urls.api + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', dataType: 'json' }).done(function (response) { var connections = response.connections; @@ -704,7 +704,7 @@ nf.GoTo = (function () { $.ajax({ type: 'GET', - url: config.urls.controller + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', + url: config.urls.api + '/process-groups/' + encodeURIComponent(selectionData.component.parentGroupId) + '/connections', dataType: 'json' }).done(function (response) { var connections = response.connections; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-label-configuration.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-label-configuration.js index c308469ddf..6e9ee362a1 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-label-configuration.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-label-configuration.js @@ -19,7 +19,7 @@ nf.LabelConfiguration = (function () { - var labelUri = ''; + var labelId = ''; return { /** @@ -33,23 +33,32 @@ nf.LabelConfiguration = (function () { buttonText: 'Apply', handler: { click: function () { - var revision = nf.Client.getRevision(); + // get the label data + var labelData = d3.select('#id-' + labelId).datum(); // get the new values var labelValue = $('#label-value').val(); var fontSize = $('#label-font-size').combo('getSelectedOption'); + // build the label entity + var labelEntity = { + 'revision': nf.Client.getRevision(), + 'label': { + 'id': labelId, + 'label': labelValue, + 'style': { + 'font-size': fontSize.value + } + } + }; + // save the new label value $.ajax({ type: 'PUT', - url: labelUri, - data: { - 'version': revision.version, - 'clientId': revision.clientId, - 'label': labelValue, - 'style[font-size]': fontSize.value - }, - dataType: 'json' + url: labelData.component.uri, + data: JSON.stringify(labelEntity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { // update the revision nf.Client.setRevision(response.revision); @@ -72,7 +81,7 @@ nf.LabelConfiguration = (function () { }], handler: { close: function () { - labelUri = ''; + labelId = ''; } } }).draggable({ @@ -130,7 +139,7 @@ nf.LabelConfiguration = (function () { } // store the label uri - labelUri = selectionData.component.uri; + labelId = selectionData.component.id; // populate the dialog $('#label-value').val(labelValue); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-label.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-label.js index 69a4758c80..5629bbb933 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-label.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-label.js @@ -526,6 +526,13 @@ nf.Label = (function () { set(labels); } }, + + /** + * Returns the entity key when marshalling an entity of this type. + */ + getEntityKey: function (d) { + return 'label'; + }, /** * Removes the specified label. diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-port-configuration.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-port-configuration.js index 0939b3a956..41278b8489 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-port-configuration.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-port-configuration.js @@ -30,37 +30,44 @@ nf.PortConfiguration = (function () { buttonText: 'Apply', handler: { click: function () { - var revision = nf.Client.getRevision(); - // get the port data to reference the uri var portId = $('#port-id').text(); var portData = d3.select('#id-' + portId).datum(); - var data = { - version: revision.version, - clientId: revision.clientId, - name: $('#port-name').val(), - comments: $('#port-comments').val() + // build the updated port + var port = { + 'id': portId, + 'name': $('#port-name').val(), + 'comments': $('#port-comments').val() }; // include the concurrent tasks if appropriate if ($('#port-concurrent-task-container').is(':visible')) { - data['concurrentlySchedulableTaskCount'] = $('#port-concurrent-tasks').val(); + port['concurrentlySchedulableTaskCount'] = $('#port-concurrent-tasks').val(); } // mark the processor disabled if appropriate if ($('#port-enabled').hasClass('checkbox-unchecked')) { - data['state'] = 'DISABLED'; + port['state'] = 'DISABLED'; } else if ($('#port-enabled').hasClass('checkbox-checked')) { - data['state'] = 'STOPPED'; + port['state'] = 'STOPPED'; } + + // build the port entity + var portEntity = { + 'revision': nf.Client.getRevision() + }; + // use bracket notation to set the key based on the type + portEntity[nf[portData.type].getEntityKey(portData)] = port; + // update the selected component $.ajax({ type: 'PUT', - data: data, + data: JSON.stringify(portEntity), url: portData.component.uri, - dataType: 'json' + dataType: 'json', + contentType: 'application/json' }).done(function (response) { // update the revision nf.Client.setRevision(response.revision); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-port.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-port.js index e0ff75d295..7b69c8b457 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-port.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-port.js @@ -606,7 +606,14 @@ nf.Port = (function () { // update the visible ports d3.selectAll('g.input-port.visible, g.output-port.visible').call(updatePortStatus); }, - + + /** + * Returns the entity key when marshalling an entity of this type. + */ + getEntityKey: function (d) { + return d.component.type === 'INPUT_PORT' ? 'inputPort' : 'outputPort'; + }, + /** * Removes the specified port. * diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-process-group-configuration.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-process-group-configuration.js index fb224118ce..b72deb2c67 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-process-group-configuration.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-process-group-configuration.js @@ -34,17 +34,23 @@ nf.ProcessGroupConfiguration = (function () { var processGroupId = $('#process-group-id').text(); var processGroupData = d3.select('#id-' + processGroupId).datum(); + // build the entity + var entity = { + 'revision': nf.Client.getRevision(), + 'processGroup': { + 'id': processGroupId, + 'name': $('#process-group-name').val(), + 'comments': $('#process-group-comments').val() + } + }; + // update the selected component $.ajax({ type: 'PUT', - data: { - version: revision.version, - clientId: revision.clientId, - name: $('#process-group-name').val(), - comments: $('#process-group-comments').val() - }, + data: JSON.stringify(entity), url: processGroupData.component.uri, - dataType: 'json' + dataType: 'json', + contentType: 'application/json' }).done(function (response) { if (nf.Common.isDefinedAndNotNull(response.processGroup)) { // update the revision diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-process-group.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-process-group.js index 32ba3af663..bde0f41d87 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-process-group.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-process-group.js @@ -1038,6 +1038,13 @@ nf.ProcessGroup = (function () { // update the visible process groups d3.selectAll('g.process-group.visible').call(updateProcessGroupStatus); }, + + /** + * Returns the entity key when marshalling an entity of this type. + */ + getEntityKey: function (d) { + return 'processGroup'; + }, /** * Removes the specified process group. diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-processor-configuration.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-processor-configuration.js index 2bbb81384e..12714801ee 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-processor-configuration.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-processor-configuration.js @@ -580,7 +580,7 @@ nf.ProcessorConfiguration = (function () { // get the processor history requests.push($.ajax({ type: 'GET', - url: '../nifi-api/controller/history/processors/' + encodeURIComponent(processor.id), + url: '../nifi-api/history/processors/' + encodeURIComponent(processor.id), dataType: 'json' })); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-processor.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-processor.js index 4b4a1ef064..e46b462bc8 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-processor.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-processor.js @@ -823,6 +823,13 @@ nf.Processor = (function () { // update the visible processor status d3.selectAll('g.processor.visible').call(updateProcessorStatus); }, + + /** + * Returns the entity key when marshalling an entity of this type. + */ + getEntityKey: function (d) { + return 'processor'; + }, /** * Returns the default color that should be used when drawing a processor. diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-queue-listing.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-queue-listing.js index 76d368ee5c..89126626e9 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-queue-listing.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-queue-listing.js @@ -381,7 +381,8 @@ nf.QueueListing = (function () { $.ajax({ type: 'POST', url: connection.component.uri + '/listing-requests', - dataType: 'json' + dataType: 'json', + contentType: 'application/json' }).done(function(response) { // initialize the progress bar value updateProgress(0); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group-configuration.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group-configuration.js index d0d5e3c882..738b5b04eb 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group-configuration.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group-configuration.js @@ -46,7 +46,6 @@ nf.RemoteProcessGroupConfiguration = (function () { data: JSON.stringify(remoteProcessGroupEntity), url: remoteProcessGroupData.component.uri, dataType: 'json', - processData: false, contentType: 'application/json' }).done(function (response) { // update the revision diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group-ports.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group-ports.js index db41bf1730..ef51f466d7 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group-ports.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group-ports.js @@ -60,7 +60,6 @@ nf.RemoteProcessGroupPorts = (function () { data: JSON.stringify(remoteProcessGroupPortEntity), url: remoteProcessGroupData.component.uri + portContextPath + encodeURIComponent(remotePortId), dataType: 'json', - processData: false, contentType: 'application/json' }).done(function (response) { // update the revision @@ -279,7 +278,6 @@ nf.RemoteProcessGroupPorts = (function () { data: JSON.stringify(remoteProcessGroupPortEntity), url: remoteProcessGroupData.component.uri + portContextPath + encodeURIComponent(port.id), dataType: 'json', - processData: false, contentType: 'application/json' }).done(function (response) { // update the revision diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group.js index 3084843573..dd7454be3f 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-remote-process-group.js @@ -1038,6 +1038,13 @@ nf.RemoteProcessGroup = (function () { // only update the visible components d3.selectAll('g.remote-process-group.visible').call(updateProcessGroupStatus); }, + + /** + * Returns the entity key when marshalling an entity of this type. + */ + getEntityKey: function (d) { + return 'remoteProcessGroup'; + }, /** * Removes the specified process group. diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-reporting-task.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-reporting-task.js index 1656185369..3cd266edfb 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-reporting-task.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-reporting-task.js @@ -189,16 +189,20 @@ nf.ReportingTask = (function () { * @param {boolean} running */ var setRunning = function (reportingTask, running) { - var revision = nf.Client.getRevision(); + var entity = { + 'revision': nf.Client.getRevision(), + 'reportingTask': { + 'id': reportingTask.id, + 'state': running === true ? 'RUNNING' : 'STOPPED' + } + }; + return $.ajax({ type: 'PUT', url: reportingTask.uri, - data: { - clientId: revision.clientId, - version: revision.version, - state: running === true ? 'RUNNING' : 'STOPPED' - }, - dataType: 'json' + data: JSON.stringify(entity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { // update the revision nf.Client.setRevision(response.revision); @@ -258,7 +262,6 @@ nf.ReportingTask = (function () { data: JSON.stringify(updatedReportingTask), url: reportingTask.uri, dataType: 'json', - processData: false, contentType: 'application/json' }).done(function (response) { if (nf.Common.isDefinedAndNotNull(response.reportingTask)) { @@ -395,7 +398,7 @@ nf.ReportingTask = (function () { // get the reporting task history var loadHistory = $.ajax({ type: 'GET', - url: '../nifi-api/controller/history/reporting-tasks/' + encodeURIComponent(reportingTask.id), + url: '../nifi-api/history/reporting-tasks/' + encodeURIComponent(reportingTask.id), dataType: 'json' }); @@ -589,7 +592,7 @@ nf.ReportingTask = (function () { // get the reporting task history var loadHistory = $.ajax({ type: 'GET', - url: '../nifi-api/controller/history/reporting-tasks/' + encodeURIComponent(reportingTask.id), + url: '../nifi-api/history/reporting-tasks/' + encodeURIComponent(reportingTask.id), dataType: 'json' }); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-secure-port-configuration.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-secure-port-configuration.js deleted file mode 100644 index 7c119c8b66..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-secure-port-configuration.js +++ /dev/null @@ -1,384 +0,0 @@ -/* - * 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. - */ -nf.SecurePortConfiguration = (function () { - - var portUri = ''; - - var config = { - search: 'User DNs, groups, etc' - }; - - /** - * Initializes the port dialog. - */ - var initPortConfigurationDialog = function () { - // initialize the properties tabs - $('#secure-port-configuration-tabs').tabbs({ - tabStyle: 'tab', - selectedTabStyle: 'selected-tab', - tabs: [{ - name: 'Settings', - tabContentId: 'secure-port-settings-tab-content' - }, { - name: 'Access Control', - tabContentId: 'secure-port-access-control-tab-content' - }] - }); - - // initialize the dialog - $('#secure-port-configuration').modal({ - headerText: 'Configure Secure Port', - overlayBackground: true, - buttons: [{ - buttonText: 'Apply', - handler: { - click: function () { - var portId = $('#secure-port-id').text(); - var portType = $('#secure-port-type').text(); - - var portDto = {}; - portDto['id'] = portId; - portDto['name'] = $('#secure-port-name').val(); - portDto['comments'] = $('#secure-port-comments').val(); - portDto['groupAccessControl'] = getAllowedGroups(); - portDto['userAccessControl'] = getAllowedUsers(); - - // include the concurrent tasks if appropriate - if ($('#secure-port-concurrent-task-container').is(':visible')) { - portDto['concurrentlySchedulableTaskCount'] = $('#secure-port-concurrent-tasks').val(); - } - - // mark the processor disabled if appropriate - if ($('#secure-port-enabled').hasClass('checkbox-unchecked')) { - portDto['state'] = 'DISABLED'; - } else if ($('#secure-port-enabled').hasClass('checkbox-checked')) { - portDto['state'] = 'STOPPED'; - } - - var portEntity = {}; - portEntity['revision'] = nf.Client.getRevision(); - portEntity[portType] = portDto; - - // update the selected component - $.ajax({ - type: 'PUT', - data: JSON.stringify(portEntity), - contentType: 'application/json', - url: portUri, - dataType: 'json' - }).done(function (response) { - // update the revision - nf.Client.setRevision(response.revision); - - var port; - if (nf.Common.isDefinedAndNotNull(response.inputPort)) { - port = response.inputPort; - } else { - port = response.outputPort; - } - - // refresh the port component - nf.Port.set(port); - - // close the details panel - $('#secure-port-configuration').modal('hide'); - }).fail(function (xhr, status, error) { - // close the details panel - $('#secure-port-configuration').modal('hide'); - - // handle the error - nf.Common.handleAjaxError(xhr, status, error); - }); - } - } - }, { - buttonText: 'Cancel', - handler: { - click: function () { - $('#secure-port-configuration').modal('hide'); - } - } - }], - handler: { - close: function () { - portUri = ''; - - // clear the port details - $('#secure-port-id').text(''); - $('#secure-port-type').text(''); - $('#secure-port-name').val(''); - $('#secure-port-enabled').removeClass('checkbox-unchecked checkbox-checked'); - $('#secure-port-concurrent-tasks').val(''); - $('#secure-port-comments').val(''); - $('#allowed-users').empty(); - $('#allowed-groups').empty(); - } - } - }).draggable({ - containment: 'parent', - handle: '.dialog-header' - }); - - // listen for removal requests - $(document).on('click', 'div.remove-allowed-entity', function () { - $(this).closest('li').remove(); - $(this).closest('ul').sortable('refresh'); - }); - - // initialize the access control auto complete - $.widget('nf.userSearchAutocomplete', $.ui.autocomplete, { - _normalize: function(searchResults) { - var items = []; - items.push(searchResults); - return items; - }, - _resizeMenu: function () { - var ul = this.menu.element; - ul.width(700); - }, - _renderMenu: function (ul, items) { - var self = this; - - // results are normalized into an array - var results = items[0]; - - // show all groups not currently selected - if (!nf.Common.isEmpty(results.userGroupResults)) { - var allowedGroups = getAllowedGroups(); - var groupHeaderAdded = false; - - // go through each group result - $.each(results.userGroupResults, function (i, groupMatch) { - - // see if this match is not already selected - if ($.inArray(groupMatch.group, allowedGroups) === -1) { - - // only add the header for the first non selected matching group - if (!groupHeaderAdded) { - ul.append('
        • Groups
        • '); - groupHeaderAdded = true; - } - - // add the group match - self._renderGroupItem(ul, groupMatch); - } - }); - } - - // show all users not currently selected - if (!nf.Common.isEmpty(results.userResults)) { - var allowedUsers = getAllowedUsers(); - var userHeaderAdded = false; - - // go through each user result - $.each(results.userResults, function (i, userMatch) { - - // see if this match is not already selected - if ($.inArray(userMatch.userDn, allowedUsers) === -1) { - - // only add the header for the first non selected matching user - if (!userHeaderAdded) { - ul.append('
        • Users
        • '); - userHeaderAdded = true; - } - - // add the user match - self._renderUserItem(ul, userMatch); - } - }); - } - - // ensure there were some results - if (ul.children().length === 0) { - ul.append('
        • No users or groups match
        • '); - } - }, - _renderGroupItem: function (ul, groupMatch) { - var groupContent = $('').append($('
          ').text(groupMatch.group)); - return $('
        • ').data('ui-autocomplete-item', groupMatch).append(groupContent).appendTo(ul); - }, - _renderUserItem: function (ul, userMatch) { - var userContent = $('').append($('
          ').text(userMatch.userDn)); - return $('
        • ').data('ui-autocomplete-item', userMatch).append(userContent).appendTo(ul); - } - }); - - // configure the autocomplete field - $('#secure-port-access-control').userSearchAutocomplete({ - minLength: 0, - appendTo: '#search-users-results', - position: { - my: 'left top', - at: 'left bottom', - offset: '0 1' - }, - source: function (request, response) { - // create the search request - $.ajax({ - type: 'GET', - data: { - q: request.term - }, - dataType: 'json', - url: '../nifi-api/controller/users/search-results' - }).done(function (searchResponse) { - response(searchResponse); - }); - }, - select: function (event, ui) { - var item = ui.item; - - // add the item appropriately - if (nf.Common.isDefinedAndNotNull(item.group)) { - addAllowedGroup(item.group); - } else { - addAllowedUser(item.userDn); - } - - // blur the search field - $(this).blur(); - - // stop event propagation - return false; - } - }).focus(function () { - // conditionally clear the text for the user to type - if ($(this).val() === config.search) { - $(this).val('').removeClass('search-users'); - } - }).blur(function () { - $(this).val(config.search).addClass('search-users'); - }).val(config.search).addClass('search-users'); - }; - - /** - * Adds the specified user to the list of allowed users. - * - * @argument {string} allowedUser The allowed user dn - */ - var addAllowedUser = function (allowedUser) { - var allowedUsers = $('#allowed-users'); - - // append the user - var user = $('').addClass('allowed-entity ellipsis').text(allowedUser).ellipsis(); - var userAction = $('
          ').addClass('remove-allowed-entity'); - $('
        • ').data('user', allowedUser).append(user).append(userAction).appendTo(allowedUsers); - }; - - /** - * Adds the specified group to the list of allowed groups. - * - * @argument {string} allowedGroup The allowed group name - */ - var addAllowedGroup = function (allowedGroup) { - var allowedGroups = $('#allowed-groups'); - - // append the group - var group = $('').addClass('allowed-entity ellipsis').text(allowedGroup).ellipsis(); - var groupAction = $('
          ').addClass('remove-allowed-entity'); - $('
        • ').data('group', allowedGroup).append(group).append(groupAction).appendTo(allowedGroups); - }; - - /** - * Gets the currently selected allowed users. - */ - var getAllowedUsers = function () { - var allowedUsers = []; - $('#allowed-users').children('li').each(function (_, allowedUser) { - var user = $(allowedUser).data('user'); - if (nf.Common.isDefinedAndNotNull(user)) { - allowedUsers.push(user); - } - }); - return allowedUsers; - }; - - /** - * Gets the currently selected allowed groups. - */ - var getAllowedGroups = function () { - var allowedGroups = []; - $('#allowed-groups').children('li').each(function (_, allowedGroup) { - var group = $(allowedGroup).data('group'); - if (nf.Common.isDefinedAndNotNull(group)) { - allowedGroups.push(group); - } - }); - return allowedGroups; - }; - - return { - init: function () { - initPortConfigurationDialog(); - }, - - /** - * Shows the details for the port specified selection. - * - * @argument {selection} selection The selection - */ - showConfiguration: function (selection) { - // if the specified component is a port, load its properties - if (nf.CanvasUtils.isInputPort(selection) || nf.CanvasUtils.isOutputPort(selection)) { - var selectionData = selection.datum(); - - // determine the port type - if (selectionData.component.type === 'INPUT_PORT') { - $('#secure-port-type').text('inputPort'); - } else { - $('#secure-port-type').text('outputPort'); - } - - // store the uri - portUri = selectionData.component.uri; - - // show concurrent tasks for root groups only - if (nf.Canvas.getParentGroupId() === null) { - $('#secure-port-concurrent-task-container').show(); - } else { - $('#secure-port-concurrent-task-container').hide(); - } - - // determine if the enabled checkbox is checked or not - var portEnableStyle = 'checkbox-checked'; - if (selectionData.component.state === 'DISABLED') { - portEnableStyle = 'checkbox-unchecked'; - } - - // populate the port settings - $('#secure-port-id').text(selectionData.component.id); - $('#secure-port-name').val(selectionData.component.name); - $('#secure-port-enabled').removeClass('checkbox-unchecked checkbox-checked').addClass(portEnableStyle); - $('#secure-port-concurrent-tasks').val(selectionData.component.concurrentlySchedulableTaskCount); - $('#secure-port-comments').val(selectionData.component.comments); - - // add allowed users - $.each(selectionData.component.userAccessControl, function (_, allowedUser) { - addAllowedUser(allowedUser); - }); - - // add allowed groups - $.each(selectionData.component.groupAccessControl, function (_, allowedGroup) { - addAllowedGroup(allowedGroup); - }); - - // show the details - $('#secure-port-configuration').modal('show'); - } - } - }; -}()); \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-secure-port-details.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-secure-port-details.js deleted file mode 100644 index 63afac01ba..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-secure-port-details.js +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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. - */ - -/* global nf */ - -nf.SecurePortDetails = (function () { - - /** - * Adds the specified user to the list of allowed users. - * - * @argument {string} allowedUser The allowed user dn - */ - var addAllowedUser = function (allowedUser) { - var allowedUsers = $('#read-only-allowed-users'); - - // append the user - var user = $('').addClass('allowed-entity ellipsis').text(allowedUser).ellipsis(); - $('
        • ').data('user', allowedUser).append(user).appendTo(allowedUsers); - }; - - /** - * Adds the specified group to the list of allowed groups. - * - * @argument {string} allowedGroup The allowed group name - */ - var addAllowedGroup = function (allowedGroup) { - var allowedGroups = $('#read-only-allowed-groups'); - - // append the group - var group = $('').addClass('allowed-entity ellipsis').text(allowedGroup).ellipsis(); - $('
        • ').data('group', allowedGroup).append(group).appendTo(allowedGroups); - }; - - return { - init: function () { - // initialize the properties tabs - $('#secure-port-details-tabs').tabbs({ - tabStyle: 'tab', - selectedTabStyle: 'selected-tab', - tabs: [{ - name: 'Settings', - tabContentId: 'read-only-secure-port-settings-tab-content' - }, { - name: 'Access Control', - tabContentId: 'read-only-secure-port-access-control-tab-content' - }] - }); - - // configure the processor details dialog - $('#secure-port-details').modal({ - headerText: 'Secure Port Details', - overlayBackground: true, - buttons: [{ - buttonText: 'Ok', - handler: { - click: function () { - // hide the dialog - $('#secure-port-details').modal('hide'); - } - } - }], - handler: { - close: function () { - // clear the processor details - nf.Common.clearField('read-only-secure-port-name'); - nf.Common.clearField('read-only-secure-port-id'); - nf.Common.clearField('read-only-secure-port-comments'); - nf.Common.clearField('read-only-secure-port-concurrent-tasks'); - - // clear the access control - $('#read-only-allowed-users').empty(); - $('#read-only-allowed-groups').empty(); - } - } - }).draggable({ - containment: 'parent', - handle: '.dialog-header' - }); - }, - - showDetails: function (selection) { - // if the specified component is a port, load its properties - if (nf.CanvasUtils.isInputPort(selection) || nf.CanvasUtils.isOutputPort(selection)) { - var selectionData = selection.datum(); - - // populate the port settings - nf.Common.populateField('read-only-secure-port-name', selectionData.component.name); - nf.Common.populateField('read-only-secure-port-id', selectionData.component.id); - nf.Common.populateField('read-only-secure-port-concurrent-tasks', selectionData.component.concurrentlySchedulableTaskCount); - nf.Common.populateField('read-only-secure-port-comments', selectionData.component.comments); - - // add allowed users - $.each(selectionData.component.userAccessControl, function (_, allowedUser) { - addAllowedUser(allowedUser); - }); - - // add allowed groups - $.each(selectionData.component.groupAccessControl, function (_, allowedGroup) { - addAllowedGroup(allowedGroup); - }); - - // show the details - $('#secure-port-details').modal('show'); - } - } - }; -}()); \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-settings.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-settings.js index 92e830bdaa..a4e627eae3 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-settings.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-settings.js @@ -30,9 +30,9 @@ nf.Settings = (function () { controllerConfig: '../nifi-api/controller/config', controllerArchive: '../nifi-api/controller/archive', controllerServiceTypes: '../nifi-api/controller/controller-service-types', - controllerServices: '../nifi-api/controller/controller-services', + controllerServices: '../nifi-api/controller-services', reportingTaskTypes: '../nifi-api/controller/reporting-task-types', - reportingTasks: '../nifi-api/controller/reporting-tasks' + reportingTasks: '../nifi-api/reporting-tasks' } }; @@ -297,8 +297,6 @@ nf.Settings = (function () { * @param {string} controllerServiceType */ var addControllerService = function (controllerServiceType) { - var revision = nf.Client.getRevision(); - // get the desired availability var availability; if (nf.Canvas.isClustered()) { @@ -306,17 +304,22 @@ nf.Settings = (function () { } else { availability = config.node; } + + // build the controller service entity + var controllerServiceEntity = { + 'revision': nf.Client.getRevision(), + 'controllerService': { + 'type': controllerServiceType + } + }; // add the new controller service var addService = $.ajax({ type: 'POST', url: config.urls.controllerServices + '/' + encodeURIComponent(availability), - data: { - version: revision.version, - clientId: revision.clientId, - type: controllerServiceType - }, - dataType: 'json' + data: JSON.stringify(controllerServiceEntity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { // update the revision nf.Client.setRevision(response.revision); @@ -1030,8 +1033,6 @@ nf.Settings = (function () { * @param {string} reportingTaskType */ var addReportingTask = function (reportingTaskType) { - var revision = nf.Client.getRevision(); - // get the desired availability var availability; if (nf.Canvas.isClustered()) { @@ -1039,17 +1040,22 @@ nf.Settings = (function () { } else { availability = config.node; } + + // build the reporting task entity + var reportingTaskEntity = { + 'revision': nf.Client.getRevision(), + 'reportingTask': { + 'type': reportingTaskType + } + }; // add the new reporting task var addTask = $.ajax({ type: 'POST', url: config.urls.reportingTasks + '/' + encodeURIComponent(availability), - data: { - version: revision.version, - clientId: revision.clientId, - type: reportingTaskType - }, - dataType: 'json' + data: JSON.stringify(reportingTaskEntity), + dataType: 'json', + contentType: 'application/json' }).done(function (response) { // update the revision nf.Client.setRevision(response.revision); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-snippet.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-snippet.js index e2e958ce64..750b36b09a 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-snippet.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-snippet.js @@ -22,7 +22,7 @@ nf.Snippet = (function () { var config = { urls: { snippets: '../nifi-api/controller/snippets', - processGroups: '../nifi-api/controller/process-groups' + processGroups: '../nifi-api/process-groups' } }; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/history/nf-history-model.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/history/nf-history-model.js index 48194b55ef..695912ce58 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/history/nf-history-model.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/history/nf-history-model.js @@ -123,7 +123,7 @@ // perform query... var xhr = $.ajax({ type: 'GET', - url: '../nifi-api/controller/history', + url: '../nifi-api/history', data: query, dataType: 'json' }).done(function (response) { diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/history/nf-history-table.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/history/nf-history-table.js index 1938d85cf1..3ffaae4d7c 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/history/nf-history-table.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/history/nf-history-table.js @@ -31,7 +31,7 @@ nf.HistoryTable = (function () { hidden: 'hidden' }, urls: { - history: '../nifi-api/controller/history' + history: '../nifi-api/history' } }; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-connection-details.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-connection-details.js index 409e811e1b..f9702ef743 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-connection-details.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-connection-details.js @@ -48,7 +48,7 @@ nf.ConnectionDetails = (function () { var initializeSourceProcessor = function (groupId, groupName, source) { return $.ajax({ type: 'GET', - url: '../nifi-api/controller/process-groups/' + encodeURIComponent(groupId) + '/processors/' + encodeURIComponent(source.id), + url: '../nifi-api/processors/' + encodeURIComponent(source.id), dataType: 'json' }).done(function (response) { var processor = response.processor; @@ -88,7 +88,7 @@ nf.ConnectionDetails = (function () { var initializeRemoteSourcePort = function (groupId, groupName, source) { return $.ajax({ type: 'GET', - url: '../nifi-api/controller/process-groups/' + encodeURIComponent(groupId) + '/remote-process-groups/' + encodeURIComponent(source.groupId), + url: '../nifi-api/remote-process-groups/' + encodeURIComponent(source.groupId), data: { verbose: true }, @@ -122,7 +122,7 @@ nf.ConnectionDetails = (function () { } else { $.ajax({ type: 'GET', - url: '../nifi-api/controller/process-groups/' + encodeURIComponent(source.groupId), + url: '../nifi-api/process-groups/' + encodeURIComponent(source.groupId), data: { verbose: true }, @@ -173,7 +173,7 @@ nf.ConnectionDetails = (function () { return $.Deferred(function (deferred) { $.ajax({ type: 'GET', - url: '../nifi-api/controller/process-groups/' + encodeURIComponent(groupId) + '/processors/' + encodeURIComponent(destination.id), + url: '../nifi-api/processors/' + encodeURIComponent(destination.id), dataType: 'json' }).done(function (response) { var processor = response.processor; @@ -218,7 +218,7 @@ nf.ConnectionDetails = (function () { var initializeDestinationRemotePort = function (groupId, groupName, destination) { return $.ajax({ type: 'GET', - url: '../nifi-api/controller/process-groups/' + encodeURIComponent(groupId) + '/remote-process-groups/' + encodeURIComponent(destination.groupId), + url: '../nifi-api/remote-process-groups/' + encodeURIComponent(destination.groupId), data: { verbose: true }, @@ -252,7 +252,7 @@ nf.ConnectionDetails = (function () { } else { $.ajax({ type: 'GET', - url: '../nifi-api/controller/process-groups/' + encodeURIComponent(destination.groupId), + url: '../nifi-api/process-groups/' + encodeURIComponent(destination.groupId), data: { verbose: true }, @@ -367,14 +367,14 @@ nf.ConnectionDetails = (function () { // get the group details var groupXhr = $.ajax({ type: 'GET', - url: '../nifi-api/controller/process-groups/' + encodeURIComponent(groupId), + url: '../nifi-api/process-groups/' + encodeURIComponent(groupId), dataType: 'json' }); // get the connection details var connectionXhr = $.ajax({ type: 'GET', - url: '../nifi-api/controller/process-groups/' + encodeURIComponent(groupId) + '/connections/' + encodeURIComponent(connectionId), + url: '../nifi-api/connections/' + encodeURIComponent(connectionId), dataType: 'json' }); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-processor-details.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-processor-details.js index 533e7bee5a..29579ddc22 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-processor-details.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-processor-details.js @@ -140,7 +140,7 @@ nf.ProcessorDetails = (function () { // load the properties for the specified processor var getProcessor = $.ajax({ type: 'GET', - url: '../nifi-api/controller/process-groups/' + encodeURIComponent(groupId) + '/processors/' + encodeURIComponent(processorId), + url: '../nifi-api/processors/' + encodeURIComponent(processorId), dataType: 'json' }).done(function (response) { if (nf.Common.isDefinedAndNotNull(response.processor)) { @@ -199,7 +199,7 @@ nf.ProcessorDetails = (function () { // get the processor history var getProcessorHistory = $.ajax({ type: 'GET', - url: '../nifi-api/controller/history/processors/' + encodeURIComponent(processorId), + url: '../nifi-api/history/processors/' + encodeURIComponent(processorId), dataType: 'json' }).done(function (response) { var processorHistory = response.componentHistory; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-status-history.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-status-history.js index 57f91fb5c1..8396ee0627 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-status-history.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/nf-status-history.js @@ -33,7 +33,8 @@ nf.StatusHistory = (function () { label: 'Label' }, urls: { - processGroups: '../nifi-api/controller/process-groups/' + api: '../nifi-api', + processGroups: '../nifi-api/process-groups/' } }; @@ -1099,7 +1100,7 @@ nf.StatusHistory = (function () { showConnectionChart: function (groupId, connectionId, selectedDescriptor) { $.ajax({ type: 'GET', - url: config.urls.processGroups + encodeURIComponent(groupId) + '/connections/' + encodeURIComponent(connectionId) + '/status/history', + url: config.urls.api + '/connections/' + encodeURIComponent(connectionId) + '/status/history', dataType: 'json' }).done(function (response) { handleStatusHistoryResponse(groupId, connectionId, response.statusHistory, config.type.connection, selectedDescriptor); @@ -1116,7 +1117,7 @@ nf.StatusHistory = (function () { showProcessorChart: function (groupId, processorId, selectedDescriptor) { $.ajax({ type: 'GET', - url: config.urls.processGroups + encodeURIComponent(groupId) + '/processors/' + encodeURIComponent(processorId) + '/status/history', + url: config.urls.api + '/processors/' + encodeURIComponent(processorId) + '/status/history', dataType: 'json' }).done(function (response) { handleStatusHistoryResponse(groupId, processorId, response.statusHistory, config.type.processor, selectedDescriptor); @@ -1150,7 +1151,7 @@ nf.StatusHistory = (function () { showRemoteProcessGroupChart: function (groupId, remoteProcessGroupId, selectedDescriptor) { $.ajax({ type: 'GET', - url: config.urls.processGroups + encodeURIComponent(groupId) + '/remote-process-groups/' + encodeURIComponent(remoteProcessGroupId) + '/status/history', + url: config.urls.api + '/remote-process-groups/' + encodeURIComponent(remoteProcessGroupId) + '/status/history', dataType: 'json' }).done(function (response) { handleStatusHistoryResponse(groupId, remoteProcessGroupId, response.statusHistory, config.type.remoteProcessGroup, selectedDescriptor); diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/summary/nf-cluster-search.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/summary/nf-cluster-search.js index 9bab660754..0c9fe36098 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/summary/nf-cluster-search.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/summary/nf-cluster-search.js @@ -22,7 +22,7 @@ nf.ClusterSearch = (function () { search: 'Search nodes', urls: { clusterSearch: '../nifi-api/cluster/search-results', - status: '../nifi-api/controller/process-groups/root/status', + status: '../nifi-api/process-groups/root/status', systemDiagnostics: '../nifi-api/system-diagnostics' } }; diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/summary/nf-summary-table.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/summary/nf-summary-table.js index 49ad85b23a..fcd59aae3a 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/summary/nf-summary-table.js +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/summary/nf-summary-table.js @@ -27,8 +27,9 @@ nf.SummaryTable = (function () { filterList: 'summary-filter-list' }, urls: { - status: '../nifi-api/controller/process-groups/root/status', - processGroups: '../nifi-api/controller/process-groups/', + api: '../nifi-api', + status: '../nifi-api/process-groups/root/status', + processGroups: '../nifi-api/process-groups/', systemDiagnostics: '../nifi-api/system-diagnostics', controllerConfig: '../nifi-api/controller/config', d3Script: 'js/d3/d3.min.js', @@ -2161,7 +2162,7 @@ nf.SummaryTable = (function () { // get the summary $.ajax({ type: 'GET', - url: config.urls.processGroups + encodeURIComponent(groupId) + '/processors/' + encodeURIComponent(processorId) + '/status', + url: config.urls.api + '/processors/' + encodeURIComponent(processorId) + '/status', data: { nodewise: true }, @@ -2218,7 +2219,7 @@ nf.SummaryTable = (function () { // get the summary $.ajax({ type: 'GET', - url: config.urls.processGroups + encodeURIComponent(groupId) + '/connections/' + encodeURIComponent(connectionId) + '/status', + url: config.urls.api + '/connections/' + encodeURIComponent(connectionId) + '/status', data: { nodewise: true }, @@ -2331,7 +2332,7 @@ nf.SummaryTable = (function () { // get the summary $.ajax({ type: 'GET', - url: config.urls.processGroups + encodeURIComponent(groupId) + '/input-ports/' + encodeURIComponent(inputPortId) + '/status', + url: config.urls.api + '/input-ports/' + encodeURIComponent(inputPortId) + '/status', data: { nodewise: true }, @@ -2383,7 +2384,7 @@ nf.SummaryTable = (function () { // get the summary $.ajax({ type: 'GET', - url: config.urls.processGroups + encodeURIComponent(groupId) + '/output-ports/' + encodeURIComponent(outputPortId) + '/status', + url: config.urls.api + '/output-ports/' + encodeURIComponent(outputPortId) + '/status', data: { nodewise: true }, @@ -2435,7 +2436,7 @@ nf.SummaryTable = (function () { // get the summary $.ajax({ type: 'GET', - url: config.urls.processGroups + encodeURIComponent(groupId) + '/remote-process-groups/' + encodeURIComponent(remoteProcessGroupId) + '/status', + url: config.urls.api + '/remote-process-groups/' + encodeURIComponent(remoteProcessGroupId) + '/status', data: { nodewise: true }, diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/users/nf-users-table.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/users/nf-users-table.js deleted file mode 100644 index 7ab4a76f71..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/users/nf-users-table.js +++ /dev/null @@ -1,1075 +0,0 @@ -/* - * 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. - */ - -/* global nf, Slick */ - -nf.UsersTable = (function () { - - /** - * Configuration object used to hold a number of configuration items. - */ - var config = { - filterText: 'Filter', - styles: { - filterList: 'users-filter-list' - }, - urls: { - users: '../nifi-api/controller/users', - userGroups: '../nifi-api/controller/user-groups' - } - }; - - /** - * Initializes the user details dialog. - */ - var initUserDetailsDialog = function () { - $('#user-details-dialog').modal({ - headerText: 'User Details', - overlayBackground: false, - buttons: [{ - buttonText: 'Ok', - handler: { - click: function () { - $('#user-details-dialog').modal('hide'); - } - } - }], - handler: { - close: function () { - // clear the details - $('#user-name-details-dialog').text(''); - $('#user-dn-details-dialog').text(''); - $('#user-created-details-dialog').text(''); - $('#user-verified-details-dialog').text(''); - $('#user-justification-details-dialog').text(''); - } - } - }); - }; - - /** - * Initializes the user roles dialog. - */ - var initUserRolesDialog = function () { - $('#user-roles-dialog').modal({ - headerText: 'User Roles', - overlayBackground: false, - buttons: [{ - buttonText: 'Apply', - handler: { - click: function () { - var userId = $('#user-id-roles-dialog').val(); - var userRoles = []; - - // function for determining if a checkbox is checked - var isChecked = function (domId) { - return $('#' + domId).hasClass('checkbox-checked'); - }; - - // determine the user roles - if (isChecked('role-admin-checkbox')) { - userRoles.push('ROLE_ADMIN'); - } - if (isChecked('role-dfm-checkbox')) { - userRoles.push('ROLE_DFM'); - } - if (isChecked('role-provenance-checkbox')) { - userRoles.push('ROLE_PROVENANCE'); - } - if (isChecked('role-monitor-checkbox')) { - userRoles.push('ROLE_MONITOR'); - } - if (isChecked('role-nifi-checkbox')) { - userRoles.push('ROLE_NIFI'); - } - if (isChecked('role-proxy-checkbox')) { - userRoles.push('ROLE_PROXY'); - } - - var userDto = {}; - userDto['id'] = userId; - userDto['authorities'] = userRoles; - - // ensure the account is active - userDto['status'] = 'ACTIVE'; - - var userEntity = {}; - userEntity['user'] = userDto; - - // update the user - $.ajax({ - type: 'PUT', - url: config.urls.users + '/' + encodeURIComponent(userId), - data: JSON.stringify(userEntity), - contentType: 'application/json', - dataType: 'json' - }).done(function (response) { - if (nf.Common.isDefinedAndNotNull(response.user)) { - var user = response.user; - - // get the table and update the row accordingly - var usersGrid = $('#users-table').data('gridInstance'); - var usersData = usersGrid.getData(); - usersData.updateItem(user.id, user); - } - }).fail(nf.Common.handleAjaxError); - - // hide the dialog - $('#user-roles-dialog').modal('hide'); - } - } - }, { - buttonText: 'Cancel', - handler: { - click: function () { - $('#user-roles-dialog').modal('hide'); - } - } - }], - handler: { - close: function () { - // uncheck every box - $('div.role-checkbox').removeClass('checkbox-checked').addClass('checkbox-unchecked'); - $('#user-id-roles-dialog').val(''); - } - } - }); - }; - - /** - * Initializes the group roles dialog. - */ - var initGroupRolesDialog = function () { - $('#group-roles-dialog').modal({ - headerText: 'Group Roles', - overlayBackground: false, - buttons: [{ - buttonText: 'Apply', - handler: { - click: function () { - var group = $('#group-name-roles-dialog').text(); - var groupRoles = []; - - // function for determining if a checkbox is checked - var isChecked = function (domId) { - return $('#' + domId).hasClass('checkbox-checked'); - }; - - // determine the user roles - if (isChecked('group-role-admin-checkbox')) { - groupRoles.push('ROLE_ADMIN'); - } - if (isChecked('group-role-dfm-checkbox')) { - groupRoles.push('ROLE_DFM'); - } - if (isChecked('group-role-provenance-checkbox')) { - groupRoles.push('ROLE_PROVENANCE'); - } - if (isChecked('group-role-monitor-checkbox')) { - groupRoles.push('ROLE_MONITOR'); - } - if (isChecked('group-role-nifi-checkbox')) { - groupRoles.push('ROLE_NIFI'); - } - if (isChecked('group-role-proxy-checkbox')) { - groupRoles.push('ROLE_PROXY'); - } - - var userGroupDto = {}; - userGroupDto['group'] = group; - userGroupDto['authorities'] = groupRoles; - - // ensure the accounts are active - userGroupDto['status'] = 'ACTIVE'; - - var userGroupEntity = {}; - userGroupEntity['userGroup'] = userGroupDto; - - // update the user - $.ajax({ - type: 'PUT', - url: config.urls.userGroups + '/' + encodeURIComponent(group), - data: JSON.stringify(userGroupEntity), - contentType: 'application/json', - dataType: 'json' - }).done(function () { - nf.UsersTable.loadUsersTable(); - }).fail(nf.Common.handleAjaxError); - - // hide the dialog - $('#group-roles-dialog').modal('hide'); - } - } - }, { - buttonText: 'Cancel', - handler: { - click: function () { - $('#group-roles-dialog').modal('hide'); - } - } - }], - handler: { - close: function () { - // uncheck every box - $('div.role-checkbox').removeClass('checkbox-checked').addClass('checkbox-unchecked'); - $('#group-name-roles-dialog').text(''); - } - } - }); - }; - - var initUserDeleteDialog = function () { - $('#user-delete-dialog').modal({ - headerText: 'Delete User', - overlayBackground: false, - buttons: [{ - buttonText: 'Delete', - handler: { - click: function () { - var userId = $('#user-id-delete-dialog').val(); - - // update the user - $.ajax({ - type: 'DELETE', - url: config.urls.users + '/' + encodeURIComponent(userId), - dataType: 'json' - }).done(function () { - nf.UsersTable.loadUsersTable(); - }).fail(nf.Common.handleAjaxError); - - // hide the dialog - $('#user-delete-dialog').modal('hide'); - } - } - }, { - buttonText: 'Cancel', - handler: { - click: function () { - $('#user-delete-dialog').modal('hide'); - } - } - }], - handler: { - close: function () { - // clear the current user - $('#user-id-delete-dialog').val(''); - $('#user-name-delete-dialog').text(''); - } - } - }); - }; - - /** - * Initializes the user revoke dialog. - */ - var initUserRevokeDialog = function () { - $('#user-revoke-dialog').modal({ - headerText: 'Revoke Access', - overlayBackground: false, - buttons: [{ - buttonText: 'Revoke', - handler: { - click: function () { - var userId = $('#user-id-revoke-dialog').val(); - - // update the user - $.ajax({ - type: 'PUT', - url: config.urls.users + '/' + encodeURIComponent(userId), - data: { - 'status': 'DISABLED' - }, - dataType: 'json' - }).done(function (response) { - if (nf.Common.isDefinedAndNotNull(response.user)) { - var user = response.user; - - // get the table and update the row accordingly - var usersGrid = $('#users-table').data('gridInstance'); - var usersData = usersGrid.getData(); - usersData.updateItem(user.id, user); - } - }).fail(nf.Common.handleAjaxError); - - // hide the dialog - $('#user-revoke-dialog').modal('hide'); - } - } - }, { - buttonText: 'Cancel', - handler: { - click: function () { - $('#user-revoke-dialog').modal('hide'); - } - } - }], - handler: { - close: function () { - // clear the current user - $('#user-id-revoke-dialog').val(''); - $('#user-name-revoke-dialog').text(''); - } - } - }); - }; - - /** - * Initializes the group revoke dialog. - */ - var initGroupRevokeDialog = function () { - $('#group-revoke-dialog').modal({ - headerText: 'Revoke Access', - overlayBackground: false, - buttons: [{ - buttonText: 'Revoke', - handler: { - click: function () { - var groupName = $('#group-name-revoke-dialog').text(); - - // update the group - $.ajax({ - type: 'PUT', - url: config.urls.userGroups + '/' + encodeURIComponent(groupName), - data: { - 'status': 'DISABLED' - }, - dataType: 'json' - }).done(function () { - nf.UsersTable.loadUsersTable(); - }).fail(nf.Common.handleAjaxError); - - // hide the dialog - $('#group-revoke-dialog').modal('hide'); - } - } - }, { - buttonText: 'Cancel', - handler: { - click: function () { - $('#group-revoke-dialog').modal('hide'); - } - } - }], - handler: { - close: function () { - // clear the current group - $('#group-name-revoke-dialog').text(''); - } - } - }); - }; - - /** - * Initializes the user revoke dialog. - */ - var initUserGroupDialog = function () { - $('#user-group-dialog').modal({ - headerText: 'Set Users Group', - overlayBackground: false, - buttons: [{ - buttonText: 'Group', - handler: { - click: function () { - var group = $.trim($('#group-name').val()); - - // ensure a group name was specified - if (group === '') { - nf.Dialog.showOkDialog({ - headerText: 'Group Users', - dialogContent: 'Group name cannot be blank.', - overlayBackground: false - }); - } else { - var userIds = $('#group-name').data('selected-user-ids'); - - var userGroupDto = {}; - userGroupDto['userIds'] = userIds; - userGroupDto['group'] = group; - - var userGroupEntity = {}; - userGroupEntity['userGroup'] = userGroupDto; - - // update the user - $.ajax({ - type: 'PUT', - url: config.urls.userGroups + '/' + encodeURIComponent(group), - data: JSON.stringify(userGroupEntity), - contentType: 'application/json', - dataType: 'json' - }).done(function () { - nf.UsersTable.loadUsersTable(); - }).fail(nf.Common.handleAjaxError); - } - - // hide the dialog - $('#user-group-dialog').modal('hide'); - } - } - }, { - buttonText: 'Cancel', - handler: { - click: function () { - $('#user-group-dialog').modal('hide'); - } - } - }], - handler: { - close: function () { - // clear the current configuration - $('#group-name').removeData('selected-user-ids'); - $('#group-name').val(''); - - // uncheck every box - $('div.group-role-checkbox').removeClass('checkbox-checked').addClass('checkbox-unchecked'); - } - } - }); - }; - - /** - * Initializes the processor list. - */ - var initUsersTable = function () { - // define the function for filtering the list - $('#users-filter').keyup(function () { - applyFilter(); - }).focus(function () { - if ($(this).hasClass(config.styles.filterList)) { - $(this).removeClass(config.styles.filterList).val(''); - } - }).blur(function () { - if ($(this).val() === '') { - $(this).addClass(config.styles.filterList).val(config.filterText); - } - }).addClass(config.styles.filterList).val(config.filterText); - - // filter type - $('#users-filter-type').combo({ - options: [{ - text: 'by user', - value: 'userName' - }, { - text: 'by group', - value: 'userGroup' - }, { - text: 'by role', - value: 'authorities' - }], - select: function (option) { - applyFilter(); - } - }); - - // add hover effect and click handler for opening the group dialog - nf.Common.addHoverEffect('#group-button', 'button-normal', 'button-over').click(function () { - groupUsers(); - }); - - // listen for browser resize events to update the page size - $(window).resize(function () { - nf.UsersTable.resetTableSize(); - }); - - // define a custom formatter for the more details column - var moreDetailsFormatter = function (row, cell, value, columnDef, dataContext) { - return ''; - }; - - // function for formatting the last accessed time - var valueFormatter = function (row, cell, value, columnDef, dataContext) { - return nf.Common.formatValue(value); - }; - - // function for formatting the property name - var roleFormatter = function (row, cell, value, columnDef, dataContext) { - var grouped = $('#group-collaspe-checkbox').hasClass('checkbox-checked'); - - // function for converting roles into human readable role names - var convertRoleNames = function () { - var roleNames = []; - $.each(value, function (i, role) { - var roleName = role; - if (role === 'ROLE_ADMIN') { - roleName = 'Administrator'; - } else if (role === 'ROLE_DFM') { - roleName = 'Data Flow Manager'; - } else if (role === 'ROLE_PROVENANCE') { - roleName = 'Provenance'; - } else if (role === 'ROLE_MONITOR') { - roleName = 'Read Only'; - } else if (role === 'ROLE_NIFI') { - roleName = 'NiFi'; - } else if (role === 'ROLE_PROXY') { - roleName = 'Proxy'; - } - roleNames.push(roleName); - }); - return roleNames.join(', '); - }; - - // generate the roles as appropriate - if (grouped && nf.Common.isDefinedAndNotNull(dataContext.userGroup)) { - if (dataContext.status === 'PENDING') { - return 'Authorization Pending'; - } else if (dataContext.status === 'DISABLED') { - return 'Access Revoked'; - } else if (nf.Common.isDefinedAndNotNull(value)) { - if (!nf.Common.isEmpty(value)) { - return convertRoleNames(); - } else { - return 'No roles set'; - } - } else { - return 'Multiple users with different roles'; - } - } else { - if (dataContext.status === 'PENDING') { - return 'Authorization Pending'; - } else if (dataContext.status === 'DISABLED') { - return 'Access Revoked'; - } else if (!nf.Common.isEmpty(value)) { - return convertRoleNames(); - } else { - return 'No roles set'; - } - } - }; - - // function for formatting the status - var statusFormatter = function (row, cell, value, columnDef, dataContext) { - var grouped = $('#group-collaspe-checkbox').hasClass('checkbox-checked'); - - // return the status as appropriate - if (nf.Common.isDefinedAndNotNull(value)) { - return value; - } else if (grouped && nf.Common.isDefinedAndNotNull(dataContext.userGroup)) { - return 'Multiple users with different status'; - } else { - return 'No status set'; - } - }; - - // function for formatting the actions column - var actionFormatter = function (row, cell, value, columnDef, dataContext) { - var grouped = $('#group-collaspe-checkbox').hasClass('checkbox-checked'); - - // if this represents a grouped row - if (nf.Common.isDefinedAndNotNull(dataContext.userGroup) && grouped) { - var actions = '   '; - } else { - // return the appropriate markup for an individual user - var actions = ''; - - if (dataContext.status === 'ACTIVE') { - actions += ' '; - - // add an ungroup active if appropriate - if (nf.Common.isDefinedAndNotNull(dataContext.userGroup)) { - actions += '  '; - } - } else { - actions += ' '; - } - } - - return actions; - }; - - // initialize the templates table - var usersColumns = [ - {id: 'moreDetails', name: ' ', sortable: false, resizable: false, formatter: moreDetailsFormatter, width: 50, maxWidth: 50}, - {id: 'userName', name: 'User', field: 'userName', sortable: true, resizable: true}, - {id: 'userGroup', name: 'Group', field: 'userGroup', sortable: true, resizable: true, formatter: valueFormatter}, - {id: 'authorities', name: 'Roles', field: 'authorities', sortable: true, resizable: true, formatter: roleFormatter}, - {id: 'lastAccessed', name: 'Last Accessed', field: 'lastAccessed', sortable: true, defaultSortAsc: false, resizable: true, formatter: valueFormatter}, - {id: 'status', name: 'Status', field: 'status', sortable: true, resizable: false, formatter: statusFormatter}, - {id: 'actions', name: ' ', sortable: false, resizable: false, formatter: actionFormatter, width: 100, maxWidth: 100} - ]; - var usersOptions = { - forceFitColumns: true, - enableTextSelectionOnCells: true, - enableCellNavigation: true, - enableColumnReorder: false, - autoEdit: false - }; - - // initialize the dataview - var usersData = new Slick.Data.DataView({ - inlineFilters: false - }); - usersData.setItems([]); - usersData.setFilterArgs({ - searchString: getFilterText(), - property: $('#users-filter-type').combo('getSelectedOption').value - }); - usersData.setFilter(filter); - - // initialize the sort - sort({ - columnId: 'userName', - sortAsc: true - }, usersData); - - // initialize the grid - var usersGrid = new Slick.Grid('#users-table', usersData, usersColumns, usersOptions); - usersGrid.setSelectionModel(new Slick.RowSelectionModel()); - usersGrid.registerPlugin(new Slick.AutoTooltips()); - usersGrid.setSortColumn('userName', true); - usersGrid.onSort.subscribe(function (e, args) { - sort({ - columnId: args.sortCol.field, - sortAsc: args.sortAsc - }, usersData); - }); - - // configure a click listener - usersGrid.onClick.subscribe(function (e, args) { - var target = $(e.target); - - // get the node at this row - var item = usersData.getItem(args.row); - - // determine the desired action - if (usersGrid.getColumns()[args.cell].id === 'actions') { - if (target.hasClass('update-group-access')) { - updateGroupAccess(item); - } else if (target.hasClass('revoke-group-access')) { - revokeGroupAccess(item); - } else if (target.hasClass('ungroup')) { - ungroup(item); - } else if (target.hasClass('update-user-access')) { - updateUserAccess(item); - } else if (target.hasClass('revoke-user-access')) { - revokeUserAccess(item); - } else if (target.hasClass('ungroup-user')) { - ungroupUser(item); - } else if (target.hasClass('delete-user-account')) { - deleteUserAccount(item); - } - } else if (usersGrid.getColumns()[args.cell].id === 'moreDetails') { - if (target.hasClass('show-user-details')) { - showUserDetails(item); - } - } - }); - - // wire up the dataview to the grid - usersData.onRowCountChanged.subscribe(function (e, args) { - usersGrid.updateRowCount(); - usersGrid.render(); - - // update the total number of displayed processors - $('#displayed-users').text(args.current); - }); - usersData.onRowsChanged.subscribe(function (e, args) { - usersGrid.invalidateRows(args.rows); - usersGrid.render(); - }); - - // hold onto an instance of the grid - $('#users-table').data('gridInstance', usersGrid); - - // initialize the number of displayed items - $('#displayed-users').text('0'); - }; - - /** - * Sorts the specified data using the specified sort details. - * - * @param {object} sortDetails - * @param {object} data - */ - var sort = function (sortDetails, data) { - // defines a function for sorting - var comparer = function (a, b) { - if (sortDetails.columnId === 'lastAccessed') { - var aDate = nf.Common.parseDateTime(a[sortDetails.columnId]); - var bDate = nf.Common.parseDateTime(b[sortDetails.columnId]); - return aDate.getTime() - bDate.getTime(); - } else { - var aString = nf.Common.isDefinedAndNotNull(a[sortDetails.columnId]) ? a[sortDetails.columnId] : ''; - var bString = nf.Common.isDefinedAndNotNull(b[sortDetails.columnId]) ? b[sortDetails.columnId] : ''; - return aString === bString ? 0 : aString > bString ? 1 : -1; - } - }; - - // perform the sort - data.sort(comparer, sortDetails.sortAsc); - }; - - /** - * Prompts to gather user group name. - */ - var groupUsers = function () { - // get the table and update the row accordingly - var usersGrid = $('#users-table').data('gridInstance'); - var selectedIndices = usersGrid.getSelectedRows(); - - if ($.isArray(selectedIndices) && selectedIndices.length > 0) { - var usersData = usersGrid.getData(); - - var userIds = []; - $.each(selectedIndices, function (_, index) { - var user = usersData.getItem(index); - - // groups have comma separated id's - userIds = userIds.concat(user['id'].split(',')); - }); - - var groupNameField = $('#group-name'); - groupNameField.data('selected-user-ids', userIds); - - // show the dialog - $('#user-group-dialog').modal('show'); - - // set the focus - groupNameField.focus(); - } else { - nf.Dialog.showOkDialog({ - headerText: 'Group Users', - dialogContent: 'Select one or more users to group.', - overlayBackground: false - }); - } - }; - - /** - * Get the text out of the filter field. If the filter field doesn't - * have any text it will contain the text 'filter list' so this method - * accounts for that. - */ - var getFilterText = function () { - var filterText = ''; - var filterField = $('#users-filter'); - if (!filterField.hasClass(config.styles.filterList)) { - filterText = filterField.val(); - } - return filterText; - }; - - /** - * Applies the filter found in the filter expression text field. - */ - var applyFilter = function () { - // get the dataview - var usersGrid = $('#users-table').data('gridInstance'); - - // ensure the grid has been initialized - if (nf.Common.isDefinedAndNotNull(usersGrid)) { - var usersData = usersGrid.getData(); - - // update the search criteria - usersData.setFilterArgs({ - searchString: getFilterText(), - property: $('#users-filter-type').combo('getSelectedOption').value - }); - usersData.refresh(); - } - }; - - /** - * Performs the filtering. - * - * @param {object} item The item subject to filtering - * @param {object} args Filter arguments - * @returns {Boolean} Whether or not to include the item - */ - var filter = function (item, args) { - if (args.searchString === '') { - return true; - } - - try { - // perform the row filtering - var filterExp = new RegExp(args.searchString, 'i'); - } catch (e) { - // invalid regex - return false; - } - - // handle searching appropriately - if (args.property === 'authorities') { - var roles = item[args.property]; - - var found = false; - for (var i = 0; i < roles.length; i++) { - var role = roles[i]; - var roleName = role; - - // convert the role name accordingly - if (role === 'ROLE_ADMIN') { - roleName = 'Administrator'; - } else if (role === 'ROLE_DFM') { - roleName = 'Data Flow Manager'; - } else if (role === 'ROLE_PROVENANCE') { - roleName = 'Provenance'; - } else if (role === 'ROLE_MONITOR') { - roleName = 'Read Only'; - } else if (role === 'ROLE_NIFI') { - roleName = 'NiFi'; - } else if (role === 'ROLE_PROXY') { - roleName = 'Proxy'; - } - - // see if the string was found - if (roleName.search(filterExp) >= 0) { - found = true; - break; - } - } - - return found; - } else { - return item[args.property].search(filterExp) >= 0; - } - }; - - /** - * Shows details for the specified user. - * - * @param {object} user - */ - var showUserDetails = function (user) { - var grouped = $('#group-collaspe-checkbox').hasClass('checkbox-checked'); - - // update the dialog fields - $('#user-name-details-dialog').text(user.userName); - $('#user-dn-details-dialog').text(user.dn); - - // handle fields that could vary for groups - if (nf.Common.isDefinedAndNotNull(user.creation)) { - $('#user-created-details-dialog').text(user.creation); - } else if (grouped && nf.Common.isDefinedAndNotNull(user.userGroup)) { - $('#user-created-details-dialog').html('Multiple users with different creation timestamps.'); - } else { - $('#user-created-details-dialog').html('No creation timestamp set'); - } - - if (nf.Common.isDefinedAndNotNull(user.lastVerified)) { - $('#user-verified-details-dialog').text(user.lastVerified); - } else if (grouped && nf.Common.isDefinedAndNotNull(user.userGroup)) { - $('#user-verified-details-dialog').html('Multiple users with different last verified timestamps.'); - } else { - $('#user-verified-details-dialog').html('No last verified timestamp set.'); - } - - if (nf.Common.isDefinedAndNotNull(user.justification)) { - $('#user-justification-details-dialog').text(user.justification); - } else if (grouped && nf.Common.isDefinedAndNotNull(user.userGroup)) { - $('#user-justification-details-dialog').html('Multiple users with different justifications.'); - } else { - $('#user-justification-details-dialog').html('No justification set.'); - } - - // show the dialog - $('#user-details-dialog').modal('show'); - }; - - /** - * Updates the specified groups level of access. - * - * @argument {object} item The user item - */ - var updateGroupAccess = function (item) { - // record the current group - $('#group-name-roles-dialog').text(item.userGroup); - - // show the dialog - $('#group-roles-dialog').modal('show'); - }; - - /** - * Disables the specified group's account. - * - * @argument {object} item The user item - */ - var revokeGroupAccess = function (item) { - // record the current group - $('#group-name-revoke-dialog').text(item.userGroup); - - // show the dialog - $('#group-revoke-dialog').modal('show'); - }; - - /** - * Ungroups the specified group. - * - * @argument {object} item The user item - */ - var ungroup = function (item) { - // prompt for ungroup - nf.Dialog.showYesNoDialog({ - dialogContent: 'Remove all users from group \'' + nf.Common.escapeHtml(item.userGroup) + '\'?', - overlayBackground: false, - yesHandler: function () { - $.ajax({ - type: 'DELETE', - url: config.urls.userGroups + '/' + encodeURIComponent(item.userGroup), - dataType: 'json' - }).done(function (response) { - nf.UsersTable.loadUsersTable(); - }).fail(nf.Common.handleAjaxError); - } - }); - }; - - /** - * Updates the specified users's level of access. - * - * @argument {object} item The user item - */ - var updateUserAccess = function (item) { - // populate the user info - $('#user-id-roles-dialog').val(item.id); - $('#user-name-roles-dialog').attr('title', item.dn).text(item.userName); - $('#user-justification-roles-dialog').html(nf.Common.formatValue(item.justification)); - - // function for checking a checkbox - var check = function (domId) { - $('#' + domId).removeClass('checkbox-unchecked').addClass('checkbox-checked'); - }; - - // go through each user role - $.each(item.authorities, function (i, authority) { - if (authority === 'ROLE_ADMIN') { - check('role-admin-checkbox'); - } else if (authority === 'ROLE_DFM') { - check('role-dfm-checkbox'); - } else if (authority === 'ROLE_PROVENANCE') { - check('role-provenance-checkbox'); - } else if (authority === 'ROLE_MONITOR') { - check('role-monitor-checkbox'); - } else if (authority === 'ROLE_NIFI') { - check('role-nifi-checkbox'); - } else if (authority === 'ROLE_PROXY') { - check('role-proxy-checkbox'); - } - }); - - // show the dialog - $('#user-roles-dialog').modal('show'); - }; - - /** - * Disables the specified user's account. - * - * @argument {object} item The user item - */ - var revokeUserAccess = function (item) { - // populate the users info - $('#user-id-revoke-dialog').val(item.id); - $('#user-name-revoke-dialog').text(item.userName); - - // show the dialog - $('#user-revoke-dialog').modal('show'); - }; - - /** - * Prompts to verify group removal. - * - * @argument {object} item The user item - */ - var ungroupUser = function (item) { - // prompt for ungroup - nf.Dialog.showYesNoDialog({ - dialogContent: 'Remove user \'' + nf.Common.escapeHtml(item.userName) + '\' from group \'' + nf.Common.escapeHtml(item.userGroup) + '\'?', - overlayBackground: false, - yesHandler: function () { - $.ajax({ - type: 'DELETE', - url: config.urls.userGroups + '/' + encodeURIComponent(item.userGroup) + '/users/' + encodeURIComponent(item.id), - dataType: 'json' - }).done(function (response) { - nf.UsersTable.loadUsersTable(); - }).fail(nf.Common.handleAjaxError); - } - }); - }; - - /** - * Delete's the specified user's account. - * - * @argument {object} item The user item - */ - var deleteUserAccount = function (item) { - // populate the users info - $('#user-id-delete-dialog').val(item.id); - $('#user-name-delete-dialog').text(item.userName); - - // show the dialog - $('#user-delete-dialog').modal('show'); - }; - - return { - init: function () { - initUserDetailsDialog(); - initUserRolesDialog(); - initGroupRolesDialog(); - initUserRevokeDialog(); - initUserDeleteDialog(); - initUserGroupDialog(); - initGroupRevokeDialog(); - initUsersTable(); - }, - - /** - * Update the size of the grid based on its container's current size. - */ - resetTableSize: function () { - var grid = $('#users-table').data('gridInstance'); - if (nf.Common.isDefinedAndNotNull(grid)) { - grid.resizeCanvas(); - } - }, - - /** - * Load the processor status table. - */ - loadUsersTable: function () { - return $.ajax({ - type: 'GET', - url: config.urls.users, - data: { - 'grouped': $('#group-collaspe-checkbox').hasClass('checkbox-checked') - }, - dataType: 'json' - }).done(function (response) { - // ensure there are users - if (nf.Common.isDefinedAndNotNull(response.users)) { - var usersGrid = $('#users-table').data('gridInstance'); - var usersData = usersGrid.getData(); - - // set the items - usersData.setItems(response.users); - usersData.reSort(); - usersGrid.invalidate(); - - // clear the current selection - usersGrid.getSelectionModel().setSelectedRows([]); - - // update the refresh timestamp - $('#users-last-refreshed').text(response.generated); - - // update the total number of processors - $('#total-users').text(response.users.length); - } else { - $('#total-users').text('0'); - } - }).fail(nf.Common.handleAjaxError); - } - }; -}()); \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/users/nf-users.js b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/users/nf-users.js deleted file mode 100644 index 9364aecb3b..0000000000 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/users/nf-users.js +++ /dev/null @@ -1,151 +0,0 @@ -/* - * 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. - */ -$(document).ready(function () { - // initialize the counters page - nf.Users.init(); -}); - -nf.Users = (function () { - - /** - * Configuration object used to hold a number of configuration items. - */ - var config = { - urls: { - banners: '../nifi-api/controller/banners', - controllerAbout: '../nifi-api/controller/about', - authorities: '../nifi-api/controller/authorities' - } - }; - - /** - * Loads the current users authorities. - */ - var loadAuthorities = function () { - return $.Deferred(function (deferred) { - $.ajax({ - type: 'GET', - url: config.urls.authorities, - dataType: 'json' - }).done(function (response) { - if (nf.Common.isDefinedAndNotNull(response.authorities)) { - // record the users authorities - nf.Common.setAuthorities(response.authorities); - deferred.resolve(response); - } else { - deferred.reject(); - } - }).fail(function (xhr, status, error) { - nf.Common.handleAjaxError(xhr, status, error); - deferred.reject(); - }); - }).promise(); - }; - - var initializeUsersPage = function () { - // define mouse over event for the refresh button - nf.Common.addHoverEffect('#refresh-button', 'button-refresh', 'button-refresh-hover').click(function () { - nf.UsersTable.loadUsersTable(); - }); - - // get the banners if we're not in the shell - return $.Deferred(function (deferred) { - if (top === window) { - $.ajax({ - type: 'GET', - url: config.urls.banners, - dataType: 'json' - }).done(function (bannerResponse) { - // ensure the banners response is specified - if (nf.Common.isDefinedAndNotNull(bannerResponse.banners)) { - if (nf.Common.isDefinedAndNotNull(bannerResponse.banners.headerText) && bannerResponse.banners.headerText !== '') { - // update the header text - var bannerHeader = $('#banner-header').text(bannerResponse.banners.headerText).show(); - - // show the banner - var updateTop = function (elementId) { - var element = $('#' + elementId); - element.css('top', (parseInt(bannerHeader.css('height'), 10) + parseInt(element.css('top'), 10)) + 'px'); - }; - - // update the position of elements affected by top banners - updateTop('users'); - } - - if (nf.Common.isDefinedAndNotNull(bannerResponse.banners.footerText) && bannerResponse.banners.footerText !== '') { - // update the footer text and show it - var bannerFooter = $('#banner-footer').text(bannerResponse.banners.footerText).show(); - - var updateBottom = function (elementId) { - var element = $('#' + elementId); - element.css('bottom', parseInt(bannerFooter.css('height'), 10) + 'px'); - }; - - // update the position of elements affected by bottom banners - updateBottom('users'); - } - } - - deferred.resolve(); - }).fail(function (xhr, status, error) { - nf.Common.handleAjaxError(xhr, status, error); - deferred.reject(); - }); - } else { - deferred.resolve(); - } - }); - }; - - return { - /** - * Initializes the counters page. - */ - init: function () { - nf.Storage.init(); - - // load the users authorities - loadAuthorities().done(function () { - // create the counters table - nf.UsersTable.init(); - - // load the users table - nf.UsersTable.loadUsersTable().done(function () { - // finish initializing users page - initializeUsersPage().done(function () { - // configure the initial grid height - nf.UsersTable.resetTableSize(); - - // get the about details - $.ajax({ - type: 'GET', - url: config.urls.controllerAbout, - dataType: 'json' - }).done(function (response) { - var aboutDetails = response.about; - var countersTitle = aboutDetails.title + ' Users'; - - // set the document title and the about title - document.title = countersTitle; - $('#users-header-text').text(countersTitle); - }).fail(nf.Common.handleAjaxError); - }); - }); - }); - } - }; -}()); \ No newline at end of file diff --git a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/pom.xml b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/pom.xml index 771a258cfc..6e79f7be53 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/pom.xml +++ b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/pom.xml @@ -33,8 +33,6 @@ nifi-framework-cluster-protocol nifi-framework-cluster-web nifi-framework-cluster - nifi-file-authorization-provider - nifi-cluster-authorization-provider nifi-user-actions nifi-framework-authorization nifi-file-authorizer diff --git a/nifi-nar-bundles/nifi-framework-bundle/pom.xml b/nifi-nar-bundles/nifi-framework-bundle/pom.xml index b4f1c55deb..9edf1f6c7e 100644 --- a/nifi-nar-bundles/nifi-framework-bundle/pom.xml +++ b/nifi-nar-bundles/nifi-framework-bundle/pom.xml @@ -38,16 +38,6 @@ nifi-framework-cluster-web 1.0.0-SNAPSHOT
          - - org.apache.nifi - nifi-file-authorization-provider - 1.0.0-SNAPSHOT - - - org.apache.nifi - nifi-cluster-authorization-provider - 1.0.0-SNAPSHOT - org.apache.nifi nifi-framework-cluster diff --git a/nifi-nar-bundles/nifi-kerberos-iaa-providers-bundle/nifi-kerberos-iaa-providers/src/main/java/org/apache/nifi/kerberos/KerberosProvider.java b/nifi-nar-bundles/nifi-kerberos-iaa-providers-bundle/nifi-kerberos-iaa-providers/src/main/java/org/apache/nifi/kerberos/KerberosProvider.java index d0636c5be6..f9856020af 100644 --- a/nifi-nar-bundles/nifi-kerberos-iaa-providers-bundle/nifi-kerberos-iaa-providers/src/main/java/org/apache/nifi/kerberos/KerberosProvider.java +++ b/nifi-nar-bundles/nifi-kerberos-iaa-providers-bundle/nifi-kerberos-iaa-providers/src/main/java/org/apache/nifi/kerberos/KerberosProvider.java @@ -24,8 +24,8 @@ import org.apache.nifi.authentication.LoginIdentityProviderConfigurationContext; import org.apache.nifi.authentication.LoginIdentityProviderInitializationContext; import org.apache.nifi.authentication.exception.IdentityAccessException; import org.apache.nifi.authentication.exception.InvalidLoginCredentialsException; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.authorization.exception.ProviderDestructionException; +import org.apache.nifi.authentication.exception.ProviderCreationException; +import org.apache.nifi.authentication.exception.ProviderDestructionException; import org.apache.nifi.util.FormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/nifi-nar-bundles/nifi-ldap-iaa-providers-bundle/nifi-ldap-iaa-providers/src/main/java/org/apache/nifi/ldap/LdapProvider.java b/nifi-nar-bundles/nifi-ldap-iaa-providers-bundle/nifi-ldap-iaa-providers/src/main/java/org/apache/nifi/ldap/LdapProvider.java index ce626d143f..3557383041 100644 --- a/nifi-nar-bundles/nifi-ldap-iaa-providers-bundle/nifi-ldap-iaa-providers/src/main/java/org/apache/nifi/ldap/LdapProvider.java +++ b/nifi-nar-bundles/nifi-ldap-iaa-providers-bundle/nifi-ldap-iaa-providers/src/main/java/org/apache/nifi/ldap/LdapProvider.java @@ -24,8 +24,8 @@ import org.apache.nifi.authentication.LoginIdentityProviderConfigurationContext; import org.apache.nifi.authentication.LoginIdentityProviderInitializationContext; import org.apache.nifi.authentication.exception.IdentityAccessException; import org.apache.nifi.authentication.exception.InvalidLoginCredentialsException; -import org.apache.nifi.authorization.exception.ProviderCreationException; -import org.apache.nifi.authorization.exception.ProviderDestructionException; +import org.apache.nifi.authentication.exception.ProviderCreationException; +import org.apache.nifi.authentication.exception.ProviderDestructionException; import org.apache.nifi.security.util.SslContextFactory; import org.apache.nifi.security.util.SslContextFactory.ClientAuth; import org.apache.nifi.util.FormatUtils;