diff --git a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AbstractAmqpServiceIntegrationTest.java b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AbstractAmqpServiceIntegrationTest.java index 665549de7b..16ccc387d4 100644 --- a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AbstractAmqpServiceIntegrationTest.java +++ b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AbstractAmqpServiceIntegrationTest.java @@ -50,7 +50,7 @@ import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.test.TestConfiguration; import org.eclipse.hawkbit.repository.test.util.TestdataFactory; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.eclipse.hawkbit.util.IpUtil; import org.junit.jupiter.api.BeforeEach; import org.mockito.Mockito; @@ -102,10 +102,10 @@ public void initListener() { protected T waitUntilIsPresent(final Callable> callable) { createConditionFactory() - .until(() -> WithSpringAuthorityRule.runAsPrivileged(() -> callable.call().isPresent())); + .until(() -> SecurityContextSwitch.runAsPrivileged(() -> callable.call().isPresent())); try { - return WithSpringAuthorityRule.runAsPrivileged(() -> callable.call().get()); + return SecurityContextSwitch.runAsPrivileged(() -> callable.call().get()); } catch (final Exception e) { return null; } @@ -429,7 +429,7 @@ protected void assertUpdateAttributes(final String controllerId, final Map { try { - final Map controllerAttributes = WithSpringAuthorityRule + final Map controllerAttributes = SecurityContextSwitch .runAsPrivileged(() -> targetManagement.getControllerAttributes(controllerId)); assertThat(controllerAttributes.size()).isEqualTo(attributes.size()); assertThat(controllerAttributes).containsAllEntriesOf(attributes); diff --git a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageDispatcherServiceIntegrationTest.java b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageDispatcherServiceIntegrationTest.java index 5e59035f78..d3ce100b39 100644 --- a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageDispatcherServiceIntegrationTest.java +++ b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageDispatcherServiceIntegrationTest.java @@ -72,7 +72,7 @@ import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; @@ -565,7 +565,7 @@ private void waitUntilTargetHasStatus(final String controllerId, final TargetUpd } private void waitUntil(final Callable callable) { - createConditionFactory().until(() -> WithSpringAuthorityRule.runAsPrivileged(callable)); + createConditionFactory().until(() -> SecurityContextSwitch.runAsPrivileged(callable)); } private void assertLatestMultiActionMessageContainsInstallMessages(final String controllerId, diff --git a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageHandlerServiceIntegrationTest.java b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageHandlerServiceIntegrationTest.java index 9e2f006f04..4889732391 100644 --- a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageHandlerServiceIntegrationTest.java +++ b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageHandlerServiceIntegrationTest.java @@ -63,7 +63,7 @@ import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; import org.eclipse.hawkbit.repository.test.util.TargetTestData; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullSource; @@ -941,7 +941,7 @@ private void registerTargetAndSendAndAssertUpdateActionStatus(final DmfActionSta private void assertAction(final Long actionId, final int messages, final Status... expectedActionStates) { createConditionFactory().await().untilAsserted(() -> { try { - WithSpringAuthorityRule.runAsPrivileged(() -> { + SecurityContextSwitch.runAsPrivileged(() -> { final List actionStatusList = deploymentManagement .findActionStatusByAction(PAGE, actionId).getContent(); @@ -979,7 +979,7 @@ private void assertActionStatusList(final Long actionId, final int statusListCou final Status... expectedActionStates) { createConditionFactory().await().untilAsserted(() -> { try { - WithSpringAuthorityRule.runAsPrivileged(() -> { + SecurityContextSwitch.runAsPrivileged(() -> { final List actionStatusList = deploymentManagement .findActionStatusByAction(PAGE, actionId).getContent(); assertThat(actionStatusList).hasSize(statusListCount); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementTest.java index 4f1822205f..eea53b11c2 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementTest.java @@ -50,7 +50,7 @@ import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; import org.eclipse.hawkbit.repository.test.util.HashGeneratorUtils; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.eclipse.hawkbit.repository.test.util.WithUser; import org.junit.jupiter.api.Test; @@ -612,7 +612,7 @@ private static byte[] randomBytes(final int len) { } private T runAsTenant(final String tenant, final Callable callable) throws Exception { - return WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), callable); + return SecurityContextSwitch.runAs(SecurityContextSwitch.withUserAndTenant("user", tenant), callable); } private SoftwareModule createSoftwareModuleForTenant(final String tenant) throws Exception { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementTest.java index 3f350892d7..35125f7d92 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementTest.java @@ -76,7 +76,7 @@ import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; import org.eclipse.hawkbit.repository.test.util.TargetTestData; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -844,7 +844,7 @@ void updateTargetAttributes() throws Exception { final String controllerId = "test123"; final Target target = testdataFactory.createTarget(controllerId); - WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { + SecurityContextSwitch.runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { addAttributeAndVerify(controllerId); addSecondAttributeAndVerify(controllerId); updateAttributeAndVerify(controllerId); @@ -999,8 +999,8 @@ public void updateTargetAttributesFailsIfTooManyEntries() throws Exception { final int allowedAttributes = quotaManagement.getMaxAttributeEntriesPerTarget(); testdataFactory.createTarget(controllerId); - assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> WithSpringAuthorityRule - .runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { + assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> SecurityContextSwitch + .runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { writeAttributes(controllerId, allowedAttributes + 1, "key", "value"); return null; })).withMessageContaining("" + allowedAttributes); @@ -1010,7 +1010,7 @@ public void updateTargetAttributesFailsIfTooManyEntries() throws Exception { // Write allowed number of attributes twice with same key should result // in update but work - WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { + SecurityContextSwitch.runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { writeAttributes(controllerId, allowedAttributes, "key", "value1"); writeAttributes(controllerId, allowedAttributes, "key", "value2"); return null; @@ -1018,8 +1018,8 @@ public void updateTargetAttributesFailsIfTooManyEntries() throws Exception { assertThat(targetManagement.getControllerAttributes(controllerId)).hasSize(10); // Now rite one more - assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> WithSpringAuthorityRule - .runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { + assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> SecurityContextSwitch + .runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { writeAttributes(controllerId, 1, "additional", "value1"); return null; })).withMessageContaining("" + allowedAttributes); @@ -1075,8 +1075,8 @@ public void controllerProvidesIntermediateFeedbackFailsIfQuotaHit() { final Long actionId = createTargetAndAssignDs(); // Fails as one entry is already in there from the assignment - assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> WithSpringAuthorityRule - .runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { + assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> SecurityContextSwitch + .runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { writeStatus(actionId, allowStatusEntries); return null; })).withMessageContaining("" + allowStatusEntries); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementTest.java index d9df01bda8..1d0297e3d2 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementTest.java @@ -81,7 +81,7 @@ import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties.TenantConfigurationKey; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -2224,7 +2224,7 @@ private static Map createInitStatusMap() { private void awaitRunningState(final Long myRolloutId) { Awaitility.await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(500)).with() - .until(() -> WithSpringAuthorityRule + .until(() -> SecurityContextSwitch .runAsPrivileged( () -> rolloutManagement.get(myRolloutId).orElseThrow(NoSuchElementException::new)) .getStatus().equals(RolloutStatus.RUNNING)); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SystemManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SystemManagementTest.java index 3120217ddc..46ed9ed9b1 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SystemManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SystemManagementTest.java @@ -23,7 +23,7 @@ import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.report.model.TenantUsage; import org.eclipse.hawkbit.repository.test.util.DisposableSqlTestDatabaseExtension; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -117,7 +117,7 @@ private byte[] createTestTenantsForSystemStatistics(final int tenants, final int for (int i = 0; i < tenants; i++) { final String tenantname = "tenant" + i; - WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("bumlux", tenantname, true, true, false, + SecurityContextSwitch.runAs(SecurityContextSwitch.withUserAndTenant("bumlux", tenantname, true, true, false, SpringEvalExpressions.SYSTEM_ROLE), () -> { systemManagement.getTenantMetadata(tenantname); if (artifactSize > 0) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementTest.java index 94c97ce49d..0865039473 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementTest.java @@ -68,7 +68,7 @@ import org.eclipse.hawkbit.repository.model.TargetTypeAssignmentResult; import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.eclipse.hawkbit.repository.test.util.WithUser; import org.junit.jupiter.api.Test; import org.springframework.data.domain.Page; @@ -183,16 +183,16 @@ void getTargetSecurityTokenOnlyWithCorrectPermission() throws Exception { .create(entityFactory.target().create().controllerId("targetWithSecurityToken").securityToken("token")); // retrieve security token only with READ_TARGET_SEC_TOKEN permission - final String securityTokenWithReadPermission = WithSpringAuthorityRule.runAs( - WithSpringAuthorityRule.withUser("OnlyTargetReadPermission", false, SpPermission.READ_TARGET_SEC_TOKEN), + final String securityTokenWithReadPermission = SecurityContextSwitch.runAs( + SecurityContextSwitch.withUser("OnlyTargetReadPermission", false, SpPermission.READ_TARGET_SEC_TOKEN), createdTarget::getSecurityToken); // retrieve security token as system code execution final String securityTokenAsSystemCode = systemSecurityContext.runAsSystem(createdTarget::getSecurityToken); // retrieve security token without any permissions - final String securityTokenWithoutPermission = WithSpringAuthorityRule - .runAs(WithSpringAuthorityRule.withUser("NoPermission", false), createdTarget::getSecurityToken); + final String securityTokenWithoutPermission = SecurityContextSwitch + .runAs(SecurityContextSwitch.withUser("NoPermission", false), createdTarget::getSecurityToken); assertThat(createdTarget.getSecurityToken()).isEqualTo("token"); assertThat(securityTokenWithReadPermission).isNotNull(); @@ -871,7 +871,7 @@ void targetCanBeReadWithOnlyReadTargetPermission() throws Exception { final String knownTargetControllerId = "readTarget"; controllerManagement.findOrRegisterTargetIfItDoesNotExist(knownTargetControllerId, new URI("http://127.0.0.1")); - WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUser("bumlux", "READ_TARGET"), () -> { + SecurityContextSwitch.runAs(SecurityContextSwitch.withUser("bumlux", "READ_TARGET"), () -> { final Target findTargetByControllerID = targetManagement.getByControllerID(knownTargetControllerId) .orElseThrow(IllegalStateException::new); assertThat(findTargetByControllerID).isNotNull(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java index 7ad4e4e143..9ca6fcc920 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java @@ -21,7 +21,7 @@ import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.test.util.DisposableSqlTestDatabaseExtension; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.eclipse.hawkbit.repository.test.util.WithUser; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -115,7 +115,7 @@ public void getTenanatMetdata() throws Exception { // check that the cache is not getting in the way, i.e. "bumlux" results // in bumlux and not // mytenant - assertThat(WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", "bumlux"), + assertThat(SecurityContextSwitch.runAs(SecurityContextSwitch.withUserAndTenant("user", "bumlux"), () -> systemManagement.getTenantMetadata().getTenant().toUpperCase())) .isEqualTo("bumlux".toUpperCase()); } @@ -169,7 +169,7 @@ public void createMultipleDistributionSetsWithSameNameForDifferentTenants() thro } private T runAsTenant(final String tenant, final Callable callable) throws Exception { - return WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), callable); + return SecurityContextSwitch.runAs(SecurityContextSwitch.withUserAndTenant("user", tenant), callable); } private Target createTargetForTenant(final String controllerId, final String tenant) throws Exception { diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java index 90558467bf..84ca4d9bf2 100644 --- a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java @@ -92,7 +92,7 @@ import org.springframework.test.context.TestPropertySource; @ActiveProfiles({ "test" }) -@ExtendWith({ JUnitTestLoggerExtension.class, WithSpringAuthorityRule.class , SharedSqlTestDatabaseExtension.class }) +@ExtendWith({ JUnitTestLoggerExtension.class , SharedSqlTestDatabaseExtension.class }) @WithUser(principal = "bumlux", allSpPermissions = true, authorities = { CONTROLLER_ROLE, SYSTEM_ROLE }) @SpringBootTest @ContextConfiguration(classes = { TestConfiguration.class, TestSupportBinderAutoConfiguration.class }) @@ -391,22 +391,22 @@ public void beforeAll() throws Exception { final String description = "Updated description."; - osType = WithSpringAuthorityRule + osType = SecurityContextSwitch .runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_OS)); - osType = WithSpringAuthorityRule.runAsPrivileged(() -> softwareModuleTypeManagement + osType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement .update(entityFactory.softwareModuleType().update(osType.getId()).description(description))); - appType = WithSpringAuthorityRule.runAsPrivileged( + appType = SecurityContextSwitch.runAsPrivileged( () -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_APP, Integer.MAX_VALUE)); - appType = WithSpringAuthorityRule.runAsPrivileged(() -> softwareModuleTypeManagement + appType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement .update(entityFactory.softwareModuleType().update(appType.getId()).description(description))); - runtimeType = WithSpringAuthorityRule + runtimeType = SecurityContextSwitch .runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_RT)); - runtimeType = WithSpringAuthorityRule.runAsPrivileged(() -> softwareModuleTypeManagement + runtimeType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement .update(entityFactory.softwareModuleType().update(runtimeType.getId()).description(description))); - standardDsType = WithSpringAuthorityRule.runAsPrivileged(() -> testdataFactory.findOrCreateDefaultTestDsType()); + standardDsType = SecurityContextSwitch.runAsPrivileged(() -> testdataFactory.findOrCreateDefaultTestDsType()); // publish the reset counter market event to reset the counters after // setup. The setup is transparent by the test and its @ExpectedEvent diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/CleanupTestExecutionListener.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/CleanupTestExecutionListener.java index f8ab99465e..c309692cdc 100644 --- a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/CleanupTestExecutionListener.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/CleanupTestExecutionListener.java @@ -25,7 +25,7 @@ public class CleanupTestExecutionListener extends AbstractTestExecutionListener @Override public void afterTestMethod(final TestContext testContext) throws Exception { - WithSpringAuthorityRule.runAsPrivileged(() -> { + SecurityContextSwitch.runAsPrivileged(() -> { final ApplicationContext applicationContext = testContext.getApplicationContext(); new JpaTestRepositoryManagement(applicationContext.getBean(TenantAwareCacheManager.class), applicationContext.getBean(SystemSecurityContext.class), diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/WithSpringAuthorityRule.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/SecurityContextSwitch.java similarity index 76% rename from hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/WithSpringAuthorityRule.java rename to hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/SecurityContextSwitch.java index 5db0499dda..07a4400f20 100644 --- a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/WithSpringAuthorityRule.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/SecurityContextSwitch.java @@ -9,6 +9,7 @@ */ package org.eclipse.hawkbit.repository.test.util; +import java.io.Serial; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.List; @@ -19,55 +20,27 @@ import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; import org.eclipse.hawkbit.im.authentication.UserPrincipal; import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder; -import org.junit.jupiter.api.extension.AfterEachCallback; -import org.junit.jupiter.api.extension.BeforeEachCallback; -import org.junit.jupiter.api.extension.ExtensionContext; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; -public class WithSpringAuthorityRule implements BeforeEachCallback, AfterEachCallback { +public class SecurityContextSwitch { public static final String DEFAULT_TENANT = "default"; - private SecurityContext oldContext; - - @Override - public void beforeEach(ExtensionContext context) throws Exception { - oldContext = SecurityContextHolder.getContext(); - WithUser annotation = getWithUserAnnotation(context); - if (annotation != null) { - if (annotation.autoCreateTenant()) { - createTenant(annotation.tenantId()); - } - setSecurityContext(annotation); - } - } - - private WithUser getWithUserAnnotation(ExtensionContext context) { - if (context.getRequiredTestMethod().isAnnotationPresent(WithUser.class)) { - return context.getRequiredTestMethod().getAnnotation(WithUser.class); - } - if(context.getRequiredTestClass().isAnnotationPresent(WithUser.class)){ - return context.getRequiredTestClass().getAnnotation(WithUser.class); - } - return null; - } - - @Override - public void afterEach(ExtensionContext context) throws Exception { - SecurityContextHolder.setContext(oldContext); - } + private static final WithUser PRIVILEDGED_USER = + createWithUser("bumlux", DEFAULT_TENANT, false, true, false, "ROLE_CONTROLLER", "ROLE_SYSTEM_CODE"); private static void setSecurityContext(final WithUser annotation) { - SecurityContextHolder.setContext(new SecurityContextWithUser(annotation)); + SecurityContextHolder.setContext(new WithUserSecurityContext(annotation)); } - public static T runAsPrivileged(final Callable callable) throws Exception { - return runAs(privilegedUser(), callable); + public static T runAsPrivileged(final Callable callable) throws Exception { + createTenant(DEFAULT_TENANT); + return runAs(PRIVILEDGED_USER, callable); } - public static T runAs(final WithUser withUser, final Callable callable) throws Exception { + public static T runAs(final WithUser withUser, final Callable callable) throws Exception { final SecurityContext oldContext = SecurityContextHolder.getContext(); setSecurityContext(withUser); if (withUser.autoCreateTenant()) { @@ -82,7 +55,7 @@ public static T runAs(final WithUser withUser, final Callable callable) private static void createTenant(final String tenantId) { final SecurityContext oldContext = SecurityContextHolder.getContext(); - setSecurityContext(privilegedUser()); + setSecurityContext(PRIVILEDGED_USER); try { SystemManagementHolder.getInstance().getSystemManagement().getTenantMetadata(tenantId); } finally { @@ -102,10 +75,6 @@ public static WithUser withUser(final String principal, final boolean allSpPermi return withUserAndTenant(principal, DEFAULT_TENANT, true, allSpPermision, false, authorities); } - public static WithUser withUser(final boolean autoCreateTenant) { - return withUserAndTenant("bumlux", DEFAULT_TENANT, autoCreateTenant, true, false); - } - public static WithUser withUserAndTenant(final String principal, final String tenant, final String... authorities) { return withUserAndTenant(principal, tenant, true, true, false, authorities); } @@ -116,10 +85,6 @@ public static WithUser withUserAndTenant(final String principal, final String te return createWithUser(principal, tenant, autoCreateTenant, allSpPermission, controller, authorities); } - private static WithUser privilegedUser() { - return createWithUser("bumlux", DEFAULT_TENANT, true, true, false, "ROLE_CONTROLLER", "ROLE_SYSTEM_CODE"); - } - private static WithUser createWithUser(final String principal, final String tenant, final boolean autoCreateTenant, final boolean allSpPermission, final boolean controller, final String... authorities) { return new WithUser() { @@ -171,12 +136,17 @@ public boolean controller() { }; } - static class SecurityContextWithUser implements SecurityContext { + static class WithUserSecurityContext implements SecurityContext { + + @Serial private static final long serialVersionUID = 1L; private final WithUser annotation; - public SecurityContextWithUser(WithUser annotation) { + public WithUserSecurityContext(final WithUser annotation) { this.annotation = annotation; + if (annotation.autoCreateTenant()) { + createTenant(annotation.tenantId()); + } } @Override @@ -214,7 +184,7 @@ private String[] getAllAuthorities(final String[] additionalAuthorities, final S @Override public boolean equals(final Object obj) { - if (obj instanceof SecurityContextWithUser otherSecurityContextWithUser) { + if (obj instanceof WithUserSecurityContext otherSecurityContextWithUser) { return Objects.equals(annotation, otherSecurityContextWithUser.annotation); } else { return false; diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/WithUser.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/WithUser.java index 25d5170712..fa97a47e0b 100644 --- a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/WithUser.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/WithUser.java @@ -83,7 +83,7 @@ class WithUserPrincipalSecurityContextFactory implements WithSecurityContextFactory { @Override public SecurityContext createSecurityContext(final WithUser withUserPrincipal) { - return new WithSpringAuthorityRule.SecurityContextWithUser(withUserPrincipal); + return new SecurityContextSwitch.WithUserSecurityContext(withUserPrincipal); } } } \ No newline at end of file diff --git a/hawkbit-rest/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java b/hawkbit-rest/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java index 588680f576..649acc0fc8 100644 --- a/hawkbit-rest/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java +++ b/hawkbit-rest/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java @@ -56,7 +56,7 @@ import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; @@ -150,7 +150,7 @@ void targetPollDoesNotModifyAuditData() throws Exception { // make a poll, audit information should not be changed, run as // controller principal! - WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), + SecurityContextSwitch.runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { mvc.perform(get(CONTROLLER_BASE, tenantAware.getCurrentTenant(), knownTargetControllerId)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); @@ -208,14 +208,14 @@ void rootRsPlugAndPlay() throws Exception { @Expect(type = TargetPollEvent.class, count = 1), @Expect(type = TenantConfigurationCreatedEvent.class, count = 1) }) void pollWithModifiedGlobalPollingTime() throws Exception { - WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUser("tenantadmin", HAS_AUTH_TENANT_CONFIGURATION), + SecurityContextSwitch.runAs(SecurityContextSwitch.withUser("tenantadmin", HAS_AUTH_TENANT_CONFIGURATION), () -> { tenantConfigurationManagement.addOrUpdateConfiguration(TenantConfigurationKey.POLLING_TIME_INTERVAL, "00:02:00"); return null; }); - WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUser("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { + SecurityContextSwitch.runAs(SecurityContextSwitch.withUser("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { mvc.perform(get(CONTROLLER_BASE, tenantAware.getCurrentTenant(), 4711)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()).andExpect(content().contentType(MediaTypes.HAL_JSON)) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:02:00"))); @@ -343,7 +343,7 @@ void rootRsPlugAndPlayIpAddress() throws Exception { final long create = System.currentTimeMillis(); // make a poll, audit information should be set on plug and play - WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), + SecurityContextSwitch.runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { mvc.perform(get(CONTROLLER_BASE, tenantAware.getCurrentTenant(), knownControllerId1)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); @@ -594,7 +594,7 @@ void testActionHistoryNegativeInput() throws Exception { void sleepTimeResponseForDifferentMaintenanceWindowParameters() throws Exception { final DistributionSet ds = testdataFactory.createDistributionSet(""); - WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUser("tenantadmin", HAS_AUTH_TENANT_CONFIGURATION), + SecurityContextSwitch.runAs(SecurityContextSwitch.withUser("tenantadmin", HAS_AUTH_TENANT_CONFIGURATION), () -> { tenantConfigurationManagement.addOrUpdateConfiguration(TenantConfigurationKey.POLLING_TIME_INTERVAL, "00:05:00"); diff --git a/hawkbit-rest/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtBasicAuthResourceTest.java b/hawkbit-rest/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtBasicAuthResourceTest.java index d9451557f9..03712b46f2 100644 --- a/hawkbit-rest/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtBasicAuthResourceTest.java +++ b/hawkbit-rest/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtBasicAuthResourceTest.java @@ -19,10 +19,8 @@ import org.eclipse.hawkbit.repository.test.util.CleanupTestExecutionListener; import org.eclipse.hawkbit.repository.test.util.JUnitTestLoggerExtension; import org.eclipse.hawkbit.repository.test.util.SharedSqlTestDatabaseExtension; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.rest.RestConfiguration; -import org.eclipse.hawkbit.rest.filter.ExcludePathAwareShallowETagFilter; import org.eclipse.hawkbit.rest.util.FilterHttpResponse; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.junit.jupiter.api.Test; @@ -46,8 +44,6 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.filter.CharacterEncodingFilter; -import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.CONTROLLER_ROLE; -import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.SYSTEM_ROLE; import static org.hamcrest.CoreMatchers.equalTo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; diff --git a/hawkbit-rest/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java b/hawkbit-rest/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java index fea2fb06b2..0986f6b77f 100644 --- a/hawkbit-rest/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java +++ b/hawkbit-rest/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java @@ -52,7 +52,7 @@ import org.eclipse.hawkbit.repository.model.RolloutGroupConditions; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.test.util.RolloutTestApprovalStrategy; -import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch; import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; @@ -1206,7 +1206,7 @@ void startingRolloutSwitchesIntoRunningStateAsync() throws Exception { private void awaitRunningState(final Long rolloutId) { Awaitility.await().atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofMillis(100)).with() - .until(() -> WithSpringAuthorityRule + .until(() -> SecurityContextSwitch .runAsPrivileged( () -> rolloutManagement.get(rolloutId).orElseThrow(NoSuchElementException::new)) .getStatus().equals(RolloutStatus.RUNNING));