From e8e8cd29c0285fc7f8b457da65ec958a62e2b36c Mon Sep 17 00:00:00 2001 From: hth <1165559068@qq.com> Date: Mon, 8 Jul 2024 10:48:51 +0800 Subject: [PATCH] add some UT for default auth plugin (#12318) --- .../config/AuthModuleStateBuilderTest.java | 24 +- .../auth/mock/MockAuthPluginServiceB.java | 68 +++++ ...s.plugin.auth.spi.server.AuthPluginService | 1 + .../AbstractAuthenticationManagerTest.java | 211 ++++++++++++++ .../LdapAuthenticationManagerTest.java | 73 +++++ .../controller/PermissionControllerTest.java | 89 ++++++ .../impl/controller/RoleControllerTest.java | 114 ++++++++ .../impl/controller/UserControllerTest.java | 262 +++++++++++++++++- 8 files changed, 829 insertions(+), 13 deletions(-) create mode 100644 auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginServiceB.java create mode 100644 plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/AbstractAuthenticationManagerTest.java create mode 100644 plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/LdapAuthenticationManagerTest.java create mode 100644 plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/PermissionControllerTest.java create mode 100644 plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/RoleControllerTest.java diff --git a/auth/src/test/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilderTest.java b/auth/src/test/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilderTest.java index 3727fa3d3..e26915981 100644 --- a/auth/src/test/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilderTest.java +++ b/auth/src/test/java/com/alibaba/nacos/auth/config/AuthModuleStateBuilderTest.java @@ -16,6 +16,7 @@ package com.alibaba.nacos.auth.config; +import com.alibaba.nacos.auth.mock.MockAuthPluginServiceB; import com.alibaba.nacos.sys.module.ModuleState; import com.alibaba.nacos.sys.utils.ApplicationUtils; import org.junit.jupiter.api.AfterEach; @@ -45,7 +46,6 @@ class AuthModuleStateBuilderTest { void setUp() throws Exception { when(context.getBean(AuthConfigs.class)).thenReturn(authConfigs); ApplicationUtils.injectContext(context); - when(authConfigs.getNacosAuthSystemType()).thenReturn("nacos"); } @AfterEach @@ -54,10 +54,32 @@ class AuthModuleStateBuilderTest { @Test void testBuild() { + when(authConfigs.getNacosAuthSystemType()).thenReturn("nacos"); + ModuleState actual = new AuthModuleStateBuilder().build(); assertFalse((Boolean) actual.getStates().get(AUTH_ENABLED)); assertFalse((Boolean) actual.getStates().get("login_page_enabled")); assertEquals("nacos", actual.getStates().get("auth_system_type")); assertTrue((Boolean) actual.getStates().get("auth_admin_request")); + + when(authConfigs.getNacosAuthSystemType()).thenReturn(MockAuthPluginServiceB.TEST_PLUGIN); + ModuleState actual2 = new AuthModuleStateBuilder().build(); + assertTrue((Boolean) actual2.getStates().get("login_page_enabled")); + assertEquals(MockAuthPluginServiceB.TEST_PLUGIN, actual2.getStates().get("auth_system_type")); + assertFalse((Boolean) actual2.getStates().get("auth_admin_request")); + } + + @Test + void testCacheable() { + AuthModuleStateBuilder authModuleStateBuilder = new AuthModuleStateBuilder(); + authModuleStateBuilder.build(); + boolean cacheable = authModuleStateBuilder.isCacheable(); + assertFalse(cacheable); + + when(authConfigs.getNacosAuthSystemType()).thenReturn(MockAuthPluginServiceB.TEST_PLUGIN); + AuthModuleStateBuilder authModuleStateBuilder2 = new AuthModuleStateBuilder(); + authModuleStateBuilder2.build(); + boolean cacheable2 = authModuleStateBuilder2.isCacheable(); + assertTrue(cacheable2); } } \ No newline at end of file diff --git a/auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginServiceB.java b/auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginServiceB.java new file mode 100644 index 000000000..0bf161a7b --- /dev/null +++ b/auth/src/test/java/com/alibaba/nacos/auth/mock/MockAuthPluginServiceB.java @@ -0,0 +1,68 @@ +/* + * Copyright 1999-2021 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.auth.mock; + +import com.alibaba.nacos.plugin.auth.api.IdentityContext; +import com.alibaba.nacos.plugin.auth.api.Permission; +import com.alibaba.nacos.plugin.auth.api.Resource; +import com.alibaba.nacos.plugin.auth.constant.ActionTypes; +import com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService; + +import java.util.Collection; +import java.util.Collections; + +public class MockAuthPluginServiceB implements AuthPluginService { + + public static final String TEST_PLUGIN = "testB"; + + public static final String IDENTITY_TEST_KEY = "identity-test-key"; + + @Override + public Collection identityNames() { + return Collections.singletonList(IDENTITY_TEST_KEY); + } + + @Override + public boolean enableAuth(ActionTypes action, String type) { + return true; + } + + @Override + public boolean validateIdentity(IdentityContext identityContext, Resource resource) { + return false; + } + + @Override + public Boolean validateAuthority(IdentityContext identityContext, Permission permission) { + return false; + } + + @Override + public String getAuthServiceName() { + return TEST_PLUGIN; + } + + @Override + public boolean isLoginEnabled() { + return true; + } + + @Override + public boolean isAdminRequest() { + return false; + } +} diff --git a/auth/src/test/resources/META-INF/services/com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService b/auth/src/test/resources/META-INF/services/com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService index 028c68cb8..9cbb51e25 100644 --- a/auth/src/test/resources/META-INF/services/com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService +++ b/auth/src/test/resources/META-INF/services/com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService @@ -15,3 +15,4 @@ # com.alibaba.nacos.auth.mock.MockAuthPluginService +com.alibaba.nacos.auth.mock.MockAuthPluginServiceB diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/AbstractAuthenticationManagerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/AbstractAuthenticationManagerTest.java new file mode 100644 index 000000000..69df77d91 --- /dev/null +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/AbstractAuthenticationManagerTest.java @@ -0,0 +1,211 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.auth.impl.authenticate; + +import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.plugin.auth.api.Permission; +import com.alibaba.nacos.plugin.auth.exception.AccessException; +import com.alibaba.nacos.plugin.auth.impl.constant.AuthConstants; +import com.alibaba.nacos.plugin.auth.impl.persistence.User; +import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl; +import com.alibaba.nacos.plugin.auth.impl.token.TokenManagerDelegate; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl; +import com.alibaba.nacos.plugin.auth.impl.utils.PasswordEncoderUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockHttpServletRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class AbstractAuthenticationManagerTest { + + @InjectMocks + private AbstractAuthenticationManager abstractAuthenticationManager; + + @Mock + private NacosUserDetailsServiceImpl userDetailsService; + + @Mock + private TokenManagerDelegate jwtTokenManager; + + @Mock + private NacosRoleServiceImpl roleService; + + private User user; + + @BeforeEach + void setUp() throws Exception { + user = new User(); + user.setUsername("nacos"); + user.setPassword(PasswordEncoderUtil.encode("test")); + } + + @Test + void testAuthenticate1() { + assertThrows(AccessException.class, () -> { + abstractAuthenticationManager.authenticate(null, "pwd"); + }); + } + + @Test + void testAuthenticate2() { + assertThrows(AccessException.class, () -> { + abstractAuthenticationManager.authenticate("nacos", null); + }); + } + + @Test + void testAuthenticate3() throws AccessException { + NacosUserDetails nacosUserDetails = new NacosUserDetails(user); + + when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails); + + when(jwtTokenManager.createToken(anyString())).thenReturn("token"); + + NacosUser nacosUser = abstractAuthenticationManager.authenticate("nacos", "test"); + + assertEquals("token", nacosUser.getToken()); + assertEquals(user.getUsername(), nacosUser.getUserName()); + } + + @Test + void testAuthenticate4() { + when(userDetailsService.loadUserByUsername(anyString())).thenReturn(null); + + assertThrows(AccessException.class, () -> { + abstractAuthenticationManager.authenticate("nacos", "test"); + }); + } + + @Test + void testAuthenticate5() { + assertThrows(AccessException.class, () -> { + abstractAuthenticationManager.authenticate(""); + }); + } + + @Test + void testAuthenticate6() throws AccessException { + NacosUser nacosUser = new NacosUser(); + + when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser); + NacosUser authenticate = abstractAuthenticationManager.authenticate("token"); + + assertEquals(nacosUser, authenticate); + } + + @Test + void testAuthenticate7() throws AccessException { + NacosUser nacosUser = new NacosUser(); + when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser); + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + mockHttpServletRequest.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.TOKEN_PREFIX + "-token"); + NacosUser authenticate = abstractAuthenticationManager.authenticate(mockHttpServletRequest); + + assertEquals(nacosUser, authenticate); + } + + @Test + void testAuthenticate8() throws AccessException { + NacosUser nacosUser = new NacosUser(); + when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser); + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + mockHttpServletRequest.addHeader(AuthConstants.AUTHORIZATION_HEADER, "token"); + mockHttpServletRequest.addParameter(Constants.ACCESS_TOKEN, "token"); + NacosUser authenticate = abstractAuthenticationManager.authenticate(mockHttpServletRequest); + + assertEquals(nacosUser, authenticate); + } + + @Test + void testAuthenticate9() throws AccessException { + NacosUserDetails nacosUserDetails = new NacosUserDetails(user); + when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails); + + when(jwtTokenManager.createToken(anyString())).thenReturn("token"); + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + mockHttpServletRequest.addHeader(AuthConstants.AUTHORIZATION_HEADER, "token"); + mockHttpServletRequest.addParameter(AuthConstants.PARAM_USERNAME, "nacos"); + mockHttpServletRequest.addParameter(AuthConstants.PARAM_PASSWORD, "test"); + NacosUser authenticate = abstractAuthenticationManager.authenticate(mockHttpServletRequest); + + assertEquals("token", authenticate.getToken()); + assertEquals(user.getUsername(), authenticate.getUserName()); + } + + @Test + void testAuthorize() { + Permission permission = new Permission(); + NacosUser nacosUser = new NacosUser(); + when(roleService.hasPermission(nacosUser, permission)).thenReturn(false); + + assertThrows(AccessException.class, () -> { + abstractAuthenticationManager.authorize(permission, nacosUser); + }); + } + + @Test + void testHasGlobalAdminRole() { + when(roleService.hasGlobalAdminRole(anyString())).thenReturn(true); + + boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole("nacos"); + + assertTrue(hasGlobalAdminRole); + } + + @Test + void testHasGlobalAdminRole2() { + when(roleService.hasGlobalAdminRole()).thenReturn(true); + + boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole(); + + assertTrue(hasGlobalAdminRole); + } + + @Test + void testHasGlobalAdminRole3() { + NacosUser nacosUser = new NacosUser("nacos"); + nacosUser.setGlobalAdmin(true); + + boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole(nacosUser); + + assertTrue(hasGlobalAdminRole); + } + + @Test + void testHasGlobalAdminRole4() { + NacosUser nacosUser = new NacosUser("nacos"); + nacosUser.setGlobalAdmin(false); + when(roleService.hasGlobalAdminRole(anyString())).thenReturn(true); + boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole(nacosUser); + + assertTrue(hasGlobalAdminRole); + } +} diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/LdapAuthenticationManagerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/LdapAuthenticationManagerTest.java new file mode 100644 index 000000000..242283db1 --- /dev/null +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/authenticate/LdapAuthenticationManagerTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.auth.impl.authenticate; + +import com.alibaba.nacos.plugin.auth.exception.AccessException; +import com.alibaba.nacos.plugin.auth.impl.persistence.User; +import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl; +import com.alibaba.nacos.plugin.auth.impl.token.TokenManagerDelegate; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl; +import com.alibaba.nacos.plugin.auth.impl.utils.PasswordEncoderUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.ldap.core.LdapTemplate; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class LdapAuthenticationManagerTest { + + @Mock + private NacosUserDetailsServiceImpl userDetailsService; + + @Mock + private TokenManagerDelegate jwtTokenManager; + + @Mock + private NacosRoleServiceImpl roleService; + + @Mock + private LdapTemplate ldapTemplate; + + private LdapAuthenticationManager ldapAuthenticationManager; + + private User user; + + @BeforeEach + void setUp() throws Exception { + user = new User(); + user.setUsername("nacos"); + user.setPassword(PasswordEncoderUtil.encode("test")); + ldapAuthenticationManager = new LdapAuthenticationManager(ldapTemplate, userDetailsService, jwtTokenManager, + roleService, "", true); + } + + @Test + void testLdapAuthenticate() throws AccessException { + NacosUserDetails nacosUserDetails = new NacosUserDetails(user); + when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails); + NacosUser authenticate = ldapAuthenticationManager.authenticate("nacos", "test"); + assertEquals(user.getUsername(), authenticate.getUserName()); + } +} diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/PermissionControllerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/PermissionControllerTest.java new file mode 100644 index 000000000..6f73ec638 --- /dev/null +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/PermissionControllerTest.java @@ -0,0 +1,89 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.auth.impl.controller; + +import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.persistence.model.Page; +import com.alibaba.nacos.plugin.auth.impl.persistence.PermissionInfo; +import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class PermissionControllerTest { + + @InjectMocks + private PermissionController permissionController; + + @Mock + private NacosRoleServiceImpl nacosRoleService; + + @BeforeEach + void setUp() throws Exception { + + } + + @Test + void testGetPermissions() { + Page permissionInfoPage = new Page(); + + when(nacosRoleService.getPermissionsFromDatabase(anyString(), anyInt(), anyInt())).thenReturn( + permissionInfoPage); + + Object permissions = permissionController.getPermissions(1, 10, "admin"); + assertEquals(permissionInfoPage, permissions); + } + + @Test + void testFuzzySearchPermission() { + Page permissionInfoPage = new Page(); + + when(nacosRoleService.findPermissionsLike4Page(anyString(), anyInt(), anyInt())).thenReturn(permissionInfoPage); + + Page permissions = permissionController.fuzzySearchPermission(1, 10, "admin"); + assertEquals(permissionInfoPage, permissions); + } + + @Test + void testAddPermission() { + + RestResult result = (RestResult) permissionController.addPermission("admin", "test", "test"); + + verify(nacosRoleService, times(1)).addPermission(anyString(), anyString(), anyString()); + assertEquals(200, result.getCode()); + } + + @Test + void testDeletePermission() { + RestResult result = (RestResult) permissionController.deletePermission("admin", "test", "test"); + + verify(nacosRoleService, times(1)).deletePermission(anyString(), anyString(), anyString()); + assertEquals(200, result.getCode()); + } + +} diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/RoleControllerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/RoleControllerTest.java new file mode 100644 index 000000000..880a687dc --- /dev/null +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/RoleControllerTest.java @@ -0,0 +1,114 @@ +/* + * Copyright 1999-2024 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.nacos.plugin.auth.impl.controller; + +import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.persistence.model.Page; +import com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo; +import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class RoleControllerTest { + + @Mock + private NacosRoleServiceImpl roleService; + + @InjectMocks + private RoleController roleController; + + @BeforeEach + void setUp() throws Exception { + + } + + @Test + void testGetRoles() { + Page rolesTest = new Page(); + + when(roleService.getRolesFromDatabase(anyString(), anyString(), anyInt(), anyInt())).thenReturn(rolesTest); + Object roles = roleController.getRoles(1, 10, "nacos", "test"); + + assertEquals(rolesTest, roles); + } + + @Test + void testFuzzySearchRole() { + + Page rolesTest = new Page(); + + when(roleService.findRolesLike4Page(anyString(), anyString(), anyInt(), anyInt())).thenReturn(rolesTest); + + Page roleInfoPage = roleController.fuzzySearchRole(1, 10, "nacos", "test"); + + assertEquals(rolesTest, roleInfoPage); + } + + @Test + void testSearchRoles() { + List test = new ArrayList<>(); + + when(roleService.findRolesLikeRoleName(anyString())).thenReturn(test); + + List list = roleController.searchRoles("test"); + assertEquals(test, list); + } + + @Test + void testAddRole() { + RestResult result = (RestResult) roleController.addRole("test", "nacos"); + + verify(roleService, times(1)).addRole(anyString(), anyString()); + + assertEquals(200, result.getCode()); + } + + @Test + void testDeleteRole1() { + RestResult result = (RestResult) roleController.deleteRole("test", null); + + verify(roleService, times(1)).deleteRole(anyString()); + + assertEquals(200, result.getCode()); + + } + + @Test + void testDeleteRole2() { + RestResult result = (RestResult) roleController.deleteRole("test", "nacos"); + + verify(roleService, times(1)).deleteRole(anyString(), anyString()); + + assertEquals(200, result.getCode()); + + } +} diff --git a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/UserControllerTest.java b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/UserControllerTest.java index 4a81301bb..3a88a98a0 100644 --- a/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/UserControllerTest.java +++ b/plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/controller/UserControllerTest.java @@ -17,29 +17,47 @@ package com.alibaba.nacos.plugin.auth.impl.controller; import com.alibaba.nacos.auth.config.AuthConfigs; +import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.persistence.model.Page; +import com.alibaba.nacos.plugin.auth.api.IdentityContext; import com.alibaba.nacos.plugin.auth.exception.AccessException; import com.alibaba.nacos.plugin.auth.impl.authenticate.IAuthenticationManager; import com.alibaba.nacos.plugin.auth.impl.constant.AuthConstants; import com.alibaba.nacos.plugin.auth.impl.constant.AuthSystemTypes; +import com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo; +import com.alibaba.nacos.plugin.auth.impl.persistence.User; +import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl; import com.alibaba.nacos.plugin.auth.impl.token.TokenManagerDelegate; import com.alibaba.nacos.plugin.auth.impl.users.NacosUser; +import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl; import com.alibaba.nacos.sys.env.EnvUtil; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; import org.springframework.mock.env.MockEnvironment; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Base64; +import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @@ -61,27 +79,32 @@ class UserControllerTest { @Mock private TokenManagerDelegate tokenManagerDelegate; + @Mock + private NacosUserDetailsServiceImpl userDetailsService; + + @Mock + private NacosRoleServiceImpl roleService; + + @InjectMocks private UserController userController; private NacosUser user; @BeforeEach void setUp() throws Exception { - userController = new UserController(); user = new NacosUser(); user.setUserName("nacos"); user.setGlobalAdmin(true); user.setToken("1234567890"); - injectObject("authConfigs", authConfigs); - injectObject("iAuthenticationManager", authenticationManager); MockEnvironment mockEnvironment = new MockEnvironment(); - mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder() - .encodeToString("SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes(StandardCharsets.UTF_8))); - mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); + mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder().encodeToString( + "SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes( + StandardCharsets.UTF_8))); + mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, + AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString()); EnvUtil.setEnvironment(mockEnvironment); - injectObject("jwtTokenManager", tokenManagerDelegate); } @Test @@ -98,9 +121,224 @@ class UserControllerTest { assertTrue(actualString.contains("\"globalAdmin\":true")); } - private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { - Field field = UserController.class.getDeclaredField(fieldName); - field.setAccessible(true); - field.set(userController, value); + @Test + void testCreateUser1() { + when(userDetailsService.getUserFromDatabase("nacos")).thenReturn(null); + RestResult result = (RestResult) userController.createUser("nacos", "test"); + assertEquals(200, result.getCode()); + } + + @Test + void testCreateUser2() { + when(userDetailsService.getUserFromDatabase("nacos")).thenReturn(new User()); + assertThrows(IllegalArgumentException.class, () -> { + userController.createUser("nacos", "test"); + }); + } + + @Test + void testCreateAdminUser1() { + when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name()); + when(authenticationManager.hasGlobalAdminRole()).thenReturn(true); + + RestResult result = (RestResult) userController.createAdminUser("test"); + + assertEquals(HttpStatus.CONFLICT.value(), result.getCode()); + } + + @Test + void testCreateAdminUser2() { + RestResult result = (RestResult) userController.createAdminUser("test"); + + assertEquals(HttpStatus.NOT_IMPLEMENTED.value(), result.getCode()); + } + + @Test + void testCreateAdminUser3() { + when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name()); + when(authenticationManager.hasGlobalAdminRole()).thenReturn(false); + ObjectNode result = (ObjectNode) userController.createAdminUser("test"); + + assertEquals("test", result.get(AuthConstants.PARAM_PASSWORD).asText()); + } + + @Test + void testDeleteUser1() { + List roleInfoList = new ArrayList<>(1); + RoleInfo testRole = new RoleInfo(); + testRole.setUsername("nacos"); + testRole.setRole(AuthConstants.GLOBAL_ADMIN_ROLE); + roleInfoList.add(testRole); + + when(roleService.getRoles(anyString())).thenReturn(roleInfoList); + + assertThrows(IllegalArgumentException.class, () -> { + userController.deleteUser("nacos"); + }); + + } + + @Test + void testDeleteUser2() { + List roleInfoList = new ArrayList<>(1); + RoleInfo testRole = new RoleInfo(); + testRole.setUsername("nacos"); + testRole.setRole("testRole"); + roleInfoList.add(testRole); + + when(roleService.getRoles(anyString())).thenReturn(roleInfoList); + + RestResult result = (RestResult) userController.deleteUser("nacos"); + assertEquals(200, result.getCode()); + } + + @Test + void testUpdateUser1() throws IOException { + + when(authConfigs.isAuthEnabled()).thenReturn(false); + when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(new User()); + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + RestResult result = (RestResult) userController.updateUser("nacos", "test", + mockHttpServletResponse, mockHttpServletRequest); + assertEquals(200, result.getCode()); + + } + + @Test + void testUpdateUser2() { + + when(authConfigs.isAuthEnabled()).thenReturn(false); + when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(null); + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + + assertThrows(IllegalArgumentException.class, () -> { + userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest); + }); + } + + @Test + void testUpdateUser3() throws IOException { + + when(authConfigs.isAuthEnabled()).thenReturn(true); + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + Object result = userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest); + + assertNull(result); + assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus()); + + } + + @Test + void testUpdateUser4() throws IOException { + + when(authConfigs.isAuthEnabled()).thenReturn(true); + when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(new User()); + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + IdentityContext identityContext = new IdentityContext(); + identityContext.setParameter(AuthConstants.NACOS_USER_KEY, user); + mockHttpServletRequest.getSession() + .setAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_CONTEXT, + identityContext); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + RestResult result = (RestResult) userController.updateUser("nacos", "test", + mockHttpServletResponse, mockHttpServletRequest); + assertEquals(200, result.getCode()); + + } + + @Test + void testUpdateUser5() throws IOException, AccessException { + + when(authConfigs.isAuthEnabled()).thenReturn(true); + when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(new User()); + when(authenticationManager.authenticate(any(MockHttpServletRequest.class))).thenReturn(user); + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + IdentityContext identityContext = new IdentityContext(); + identityContext.setParameter(AuthConstants.NACOS_USER_KEY, null); + mockHttpServletRequest.getSession() + .setAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_CONTEXT, + identityContext); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + RestResult result = (RestResult) userController.updateUser("nacos", "test", + mockHttpServletResponse, mockHttpServletRequest); + assertEquals(200, result.getCode()); + + } + + @Test + void testUpdateUser6() throws IOException, AccessException { + + when(authConfigs.isAuthEnabled()).thenReturn(true); + when(authenticationManager.authenticate(any(MockHttpServletRequest.class))).thenReturn(null); + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + IdentityContext identityContext = new IdentityContext(); + identityContext.setParameter(AuthConstants.NACOS_USER_KEY, null); + mockHttpServletRequest.getSession() + .setAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_CONTEXT, + identityContext); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + Object result = userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest); + + assertNull(result); + assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus()); + + } + + @Test + void testUpdateUser7() throws IOException, AccessException { + + when(authConfigs.isAuthEnabled()).thenReturn(true); + when(authenticationManager.authenticate(any(MockHttpServletRequest.class))).thenThrow( + new AccessException("test")); + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + IdentityContext identityContext = new IdentityContext(); + identityContext.setParameter(AuthConstants.NACOS_USER_KEY, null); + mockHttpServletRequest.getSession() + .setAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_CONTEXT, + identityContext); + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + Object result = userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest); + + assertNull(result); + assertEquals(HttpServletResponse.SC_FORBIDDEN, mockHttpServletResponse.getStatus()); + + } + + @Test + void testGetUsers() { + Page userPage = new Page<>(); + + when(userDetailsService.getUsersFromDatabase(anyInt(), anyInt(), anyString())).thenReturn(userPage); + + Page nacos = userController.getUsers(1, 10, "nacos"); + assertEquals(userPage, nacos); + } + + @Test + void testFuzzySearchUser() { + Page userPage = new Page<>(); + + when(userDetailsService.findUsersLike4Page(anyString(), anyInt(), anyInt())).thenReturn(userPage); + + Page nacos = userController.fuzzySearchUser(1, 10, "nacos"); + assertEquals(userPage, nacos); + } + + @Test + void testSearchUsersLikeUsername() { + List test = new ArrayList<>(1); + + when(userDetailsService.findUserLikeUsername(anyString())).thenReturn(test); + List list = userController.searchUsersLikeUsername("nacos"); + + assertEquals(test, list); + } + }