Remove WithSpringContextRule (#1505)

Signed-off-by: Marinov Avgustin <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2023-12-07 23:52:23 +02:00
committed by GitHub
parent aa1bad91e1
commit 1ae72d4ead
16 changed files with 69 additions and 103 deletions

View File

@@ -50,7 +50,7 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.TestConfiguration; import org.eclipse.hawkbit.repository.test.TestConfiguration;
import org.eclipse.hawkbit.repository.test.util.TestdataFactory; 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.eclipse.hawkbit.util.IpUtil;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.mockito.Mockito; import org.mockito.Mockito;
@@ -102,10 +102,10 @@ public abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpInt
protected <T> T waitUntilIsPresent(final Callable<Optional<T>> callable) { protected <T> T waitUntilIsPresent(final Callable<Optional<T>> callable) {
createConditionFactory() createConditionFactory()
.until(() -> WithSpringAuthorityRule.runAsPrivileged(() -> callable.call().isPresent())); .until(() -> SecurityContextSwitch.runAsPrivileged(() -> callable.call().isPresent()));
try { try {
return WithSpringAuthorityRule.runAsPrivileged(() -> callable.call().get()); return SecurityContextSwitch.runAsPrivileged(() -> callable.call().get());
} catch (final Exception e) { } catch (final Exception e) {
return null; return null;
} }
@@ -429,7 +429,7 @@ public abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpInt
createConditionFactory().untilAsserted(() -> { createConditionFactory().untilAsserted(() -> {
try { try {
final Map<String, String> controllerAttributes = WithSpringAuthorityRule final Map<String, String> controllerAttributes = SecurityContextSwitch
.runAsPrivileged(() -> targetManagement.getControllerAttributes(controllerId)); .runAsPrivileged(() -> targetManagement.getControllerAttributes(controllerId));
assertThat(controllerAttributes.size()).isEqualTo(attributes.size()); assertThat(controllerAttributes.size()).isEqualTo(attributes.size());
assertThat(controllerAttributes).containsAllEntriesOf(attributes); assertThat(controllerAttributes).containsAllEntriesOf(attributes);

View File

@@ -72,7 +72,7 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; 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.api.Test;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.EnumSource;
@@ -565,7 +565,7 @@ public class AmqpMessageDispatcherServiceIntegrationTest extends AbstractAmqpSer
} }
private void waitUntil(final Callable<Boolean> callable) { private void waitUntil(final Callable<Boolean> callable) {
createConditionFactory().until(() -> WithSpringAuthorityRule.runAsPrivileged(callable)); createConditionFactory().until(() -> SecurityContextSwitch.runAsPrivileged(callable));
} }
private void assertLatestMultiActionMessageContainsInstallMessages(final String controllerId, private void assertLatestMultiActionMessageContainsInstallMessages(final String controllerId,

View File

@@ -63,7 +63,7 @@ import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.repository.test.util.TargetTestData; 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.api.Test;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.NullSource;
@@ -941,7 +941,7 @@ class AmqpMessageHandlerServiceIntegrationTest extends AbstractAmqpServiceIntegr
private void assertAction(final Long actionId, final int messages, final Status... expectedActionStates) { private void assertAction(final Long actionId, final int messages, final Status... expectedActionStates) {
createConditionFactory().await().untilAsserted(() -> { createConditionFactory().await().untilAsserted(() -> {
try { try {
WithSpringAuthorityRule.runAsPrivileged(() -> { SecurityContextSwitch.runAsPrivileged(() -> {
final List<ActionStatus> actionStatusList = deploymentManagement final List<ActionStatus> actionStatusList = deploymentManagement
.findActionStatusByAction(PAGE, actionId).getContent(); .findActionStatusByAction(PAGE, actionId).getContent();
@@ -979,7 +979,7 @@ class AmqpMessageHandlerServiceIntegrationTest extends AbstractAmqpServiceIntegr
final Status... expectedActionStates) { final Status... expectedActionStates) {
createConditionFactory().await().untilAsserted(() -> { createConditionFactory().await().untilAsserted(() -> {
try { try {
WithSpringAuthorityRule.runAsPrivileged(() -> { SecurityContextSwitch.runAsPrivileged(() -> {
final List<ActionStatus> actionStatusList = deploymentManagement final List<ActionStatus> actionStatusList = deploymentManagement
.findActionStatusByAction(PAGE, actionId).getContent(); .findActionStatusByAction(PAGE, actionId).getContent();
assertThat(actionStatusList).hasSize(statusListCount); assertThat(actionStatusList).hasSize(statusListCount);

View File

@@ -50,7 +50,7 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.repository.test.util.HashGeneratorUtils; 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.eclipse.hawkbit.repository.test.util.WithUser;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -612,7 +612,7 @@ public class ArtifactManagementTest extends AbstractJpaIntegrationTest {
} }
private <T> T runAsTenant(final String tenant, final Callable<T> callable) throws Exception { private <T> T runAsTenant(final String tenant, final Callable<T> 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 { private SoftwareModule createSoftwareModuleForTenant(final String tenant) throws Exception {

View File

@@ -76,7 +76,7 @@ import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.repository.test.util.TargetTestData; 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.api.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -844,7 +844,7 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
final String controllerId = "test123"; final String controllerId = "test123";
final Target target = testdataFactory.createTarget(controllerId); final Target target = testdataFactory.createTarget(controllerId);
WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { SecurityContextSwitch.runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> {
addAttributeAndVerify(controllerId); addAttributeAndVerify(controllerId);
addSecondAttributeAndVerify(controllerId); addSecondAttributeAndVerify(controllerId);
updateAttributeAndVerify(controllerId); updateAttributeAndVerify(controllerId);
@@ -999,8 +999,8 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
final int allowedAttributes = quotaManagement.getMaxAttributeEntriesPerTarget(); final int allowedAttributes = quotaManagement.getMaxAttributeEntriesPerTarget();
testdataFactory.createTarget(controllerId); testdataFactory.createTarget(controllerId);
assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> WithSpringAuthorityRule assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> SecurityContextSwitch
.runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { .runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> {
writeAttributes(controllerId, allowedAttributes + 1, "key", "value"); writeAttributes(controllerId, allowedAttributes + 1, "key", "value");
return null; return null;
})).withMessageContaining("" + allowedAttributes); })).withMessageContaining("" + allowedAttributes);
@@ -1010,7 +1010,7 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
// Write allowed number of attributes twice with same key should result // Write allowed number of attributes twice with same key should result
// in update but work // 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", "value1");
writeAttributes(controllerId, allowedAttributes, "key", "value2"); writeAttributes(controllerId, allowedAttributes, "key", "value2");
return null; return null;
@@ -1018,8 +1018,8 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetManagement.getControllerAttributes(controllerId)).hasSize(10); assertThat(targetManagement.getControllerAttributes(controllerId)).hasSize(10);
// Now rite one more // Now rite one more
assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> WithSpringAuthorityRule assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> SecurityContextSwitch
.runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { .runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> {
writeAttributes(controllerId, 1, "additional", "value1"); writeAttributes(controllerId, 1, "additional", "value1");
return null; return null;
})).withMessageContaining("" + allowedAttributes); })).withMessageContaining("" + allowedAttributes);
@@ -1075,8 +1075,8 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
final Long actionId = createTargetAndAssignDs(); final Long actionId = createTargetAndAssignDs();
// Fails as one entry is already in there from the assignment // Fails as one entry is already in there from the assignment
assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> WithSpringAuthorityRule assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> SecurityContextSwitch
.runAs(WithSpringAuthorityRule.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> { .runAs(SecurityContextSwitch.withController("controller", CONTROLLER_ROLE_ANONYMOUS), () -> {
writeStatus(actionId, allowStatusEntries); writeStatus(actionId, allowStatusEntries);
return null; return null;
})).withMessageContaining("" + allowStatusEntries); })).withMessageContaining("" + allowStatusEntries);

View File

@@ -81,7 +81,7 @@ import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus;
import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; 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.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties.TenantConfigurationKey;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -2224,7 +2224,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
private void awaitRunningState(final Long myRolloutId) { private void awaitRunningState(final Long myRolloutId) {
Awaitility.await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(500)).with() Awaitility.await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(500)).with()
.until(() -> WithSpringAuthorityRule .until(() -> SecurityContextSwitch
.runAsPrivileged( .runAsPrivileged(
() -> rolloutManagement.get(myRolloutId).orElseThrow(NoSuchElementException::new)) () -> rolloutManagement.get(myRolloutId).orElseThrow(NoSuchElementException::new))
.getStatus().equals(RolloutStatus.RUNNING)); .getStatus().equals(RolloutStatus.RUNNING));

View File

@@ -23,7 +23,7 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.report.model.TenantUsage; import org.eclipse.hawkbit.repository.report.model.TenantUsage;
import org.eclipse.hawkbit.repository.test.util.DisposableSqlTestDatabaseExtension; 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.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@@ -117,7 +117,7 @@ public class SystemManagementTest extends AbstractJpaIntegrationTest {
for (int i = 0; i < tenants; i++) { for (int i = 0; i < tenants; i++) {
final String tenantname = "tenant" + 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), () -> { SpringEvalExpressions.SYSTEM_ROLE), () -> {
systemManagement.getTenantMetadata(tenantname); systemManagement.getTenantMetadata(tenantname);
if (artifactSize > 0) { if (artifactSize > 0) {

View File

@@ -68,7 +68,7 @@ import org.eclipse.hawkbit.repository.model.TargetType;
import org.eclipse.hawkbit.repository.model.TargetTypeAssignmentResult; import org.eclipse.hawkbit.repository.model.TargetTypeAssignmentResult;
import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; 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.repository.test.util.WithUser;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
@@ -183,16 +183,16 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.create(entityFactory.target().create().controllerId("targetWithSecurityToken").securityToken("token")); .create(entityFactory.target().create().controllerId("targetWithSecurityToken").securityToken("token"));
// retrieve security token only with READ_TARGET_SEC_TOKEN permission // retrieve security token only with READ_TARGET_SEC_TOKEN permission
final String securityTokenWithReadPermission = WithSpringAuthorityRule.runAs( final String securityTokenWithReadPermission = SecurityContextSwitch.runAs(
WithSpringAuthorityRule.withUser("OnlyTargetReadPermission", false, SpPermission.READ_TARGET_SEC_TOKEN), SecurityContextSwitch.withUser("OnlyTargetReadPermission", false, SpPermission.READ_TARGET_SEC_TOKEN),
createdTarget::getSecurityToken); createdTarget::getSecurityToken);
// retrieve security token as system code execution // retrieve security token as system code execution
final String securityTokenAsSystemCode = systemSecurityContext.runAsSystem(createdTarget::getSecurityToken); final String securityTokenAsSystemCode = systemSecurityContext.runAsSystem(createdTarget::getSecurityToken);
// retrieve security token without any permissions // retrieve security token without any permissions
final String securityTokenWithoutPermission = WithSpringAuthorityRule final String securityTokenWithoutPermission = SecurityContextSwitch
.runAs(WithSpringAuthorityRule.withUser("NoPermission", false), createdTarget::getSecurityToken); .runAs(SecurityContextSwitch.withUser("NoPermission", false), createdTarget::getSecurityToken);
assertThat(createdTarget.getSecurityToken()).isEqualTo("token"); assertThat(createdTarget.getSecurityToken()).isEqualTo("token");
assertThat(securityTokenWithReadPermission).isNotNull(); assertThat(securityTokenWithReadPermission).isNotNull();
@@ -871,7 +871,7 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
final String knownTargetControllerId = "readTarget"; final String knownTargetControllerId = "readTarget";
controllerManagement.findOrRegisterTargetIfItDoesNotExist(knownTargetControllerId, new URI("http://127.0.0.1")); 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) final Target findTargetByControllerID = targetManagement.getByControllerID(knownTargetControllerId)
.orElseThrow(IllegalStateException::new); .orElseThrow(IllegalStateException::new);
assertThat(findTargetByControllerID).isNotNull(); assertThat(findTargetByControllerID).isNotNull();

View File

@@ -21,7 +21,7 @@ import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.test.util.DisposableSqlTestDatabaseExtension; 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.eclipse.hawkbit.repository.test.util.WithUser;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@@ -115,7 +115,7 @@ public class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
// check that the cache is not getting in the way, i.e. "bumlux" results // check that the cache is not getting in the way, i.e. "bumlux" results
// in bumlux and not // in bumlux and not
// mytenant // mytenant
assertThat(WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", "bumlux"), assertThat(SecurityContextSwitch.runAs(SecurityContextSwitch.withUserAndTenant("user", "bumlux"),
() -> systemManagement.getTenantMetadata().getTenant().toUpperCase())) () -> systemManagement.getTenantMetadata().getTenant().toUpperCase()))
.isEqualTo("bumlux".toUpperCase()); .isEqualTo("bumlux".toUpperCase());
} }
@@ -169,7 +169,7 @@ public class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
} }
private <T> T runAsTenant(final String tenant, final Callable<T> callable) throws Exception { private <T> T runAsTenant(final String tenant, final Callable<T> 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 { private Target createTargetForTenant(final String controllerId, final String tenant) throws Exception {

View File

@@ -92,7 +92,7 @@ import org.springframework.test.context.TestExecutionListeners.MergeMode;
import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.TestPropertySource;
@ActiveProfiles({ "test" }) @ActiveProfiles({ "test" })
@ExtendWith({ JUnitTestLoggerExtension.class, WithSpringAuthorityRule.class , SharedSqlTestDatabaseExtension.class }) @ExtendWith({ JUnitTestLoggerExtension.class , SharedSqlTestDatabaseExtension.class })
@WithUser(principal = "bumlux", allSpPermissions = true, authorities = { CONTROLLER_ROLE, SYSTEM_ROLE }) @WithUser(principal = "bumlux", allSpPermissions = true, authorities = { CONTROLLER_ROLE, SYSTEM_ROLE })
@SpringBootTest @SpringBootTest
@ContextConfiguration(classes = { TestConfiguration.class, TestSupportBinderAutoConfiguration.class }) @ContextConfiguration(classes = { TestConfiguration.class, TestSupportBinderAutoConfiguration.class })
@@ -391,22 +391,22 @@ public abstract class AbstractIntegrationTest {
final String description = "Updated description."; final String description = "Updated description.";
osType = WithSpringAuthorityRule osType = SecurityContextSwitch
.runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_OS)); .runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_OS));
osType = WithSpringAuthorityRule.runAsPrivileged(() -> softwareModuleTypeManagement osType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement
.update(entityFactory.softwareModuleType().update(osType.getId()).description(description))); .update(entityFactory.softwareModuleType().update(osType.getId()).description(description)));
appType = WithSpringAuthorityRule.runAsPrivileged( appType = SecurityContextSwitch.runAsPrivileged(
() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_APP, Integer.MAX_VALUE)); () -> 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))); .update(entityFactory.softwareModuleType().update(appType.getId()).description(description)));
runtimeType = WithSpringAuthorityRule runtimeType = SecurityContextSwitch
.runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_RT)); .runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_RT));
runtimeType = WithSpringAuthorityRule.runAsPrivileged(() -> softwareModuleTypeManagement runtimeType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement
.update(entityFactory.softwareModuleType().update(runtimeType.getId()).description(description))); .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 // publish the reset counter market event to reset the counters after
// setup. The setup is transparent by the test and its @ExpectedEvent // setup. The setup is transparent by the test and its @ExpectedEvent

View File

@@ -25,7 +25,7 @@ public class CleanupTestExecutionListener extends AbstractTestExecutionListener
@Override @Override
public void afterTestMethod(final TestContext testContext) throws Exception { public void afterTestMethod(final TestContext testContext) throws Exception {
WithSpringAuthorityRule.runAsPrivileged(() -> { SecurityContextSwitch.runAsPrivileged(() -> {
final ApplicationContext applicationContext = testContext.getApplicationContext(); final ApplicationContext applicationContext = testContext.getApplicationContext();
new JpaTestRepositoryManagement(applicationContext.getBean(TenantAwareCacheManager.class), new JpaTestRepositoryManagement(applicationContext.getBean(TenantAwareCacheManager.class),
applicationContext.getBean(SystemSecurityContext.class), applicationContext.getBean(SystemSecurityContext.class),

View File

@@ -9,6 +9,7 @@
*/ */
package org.eclipse.hawkbit.repository.test.util; package org.eclipse.hawkbit.repository.test.util;
import java.io.Serial;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@@ -19,52 +20,24 @@ import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails;
import org.eclipse.hawkbit.im.authentication.UserPrincipal; import org.eclipse.hawkbit.im.authentication.UserPrincipal;
import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder; 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.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
public class WithSpringAuthorityRule implements BeforeEachCallback, AfterEachCallback { public class SecurityContextSwitch {
public static final String DEFAULT_TENANT = "default"; public static final String DEFAULT_TENANT = "default";
private SecurityContext oldContext; private static final WithUser PRIVILEDGED_USER =
createWithUser("bumlux", DEFAULT_TENANT, false, true, false, "ROLE_CONTROLLER", "ROLE_SYSTEM_CODE");
@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 void setSecurityContext(final WithUser annotation) { private static void setSecurityContext(final WithUser annotation) {
SecurityContextHolder.setContext(new SecurityContextWithUser(annotation)); SecurityContextHolder.setContext(new WithUserSecurityContext(annotation));
} }
public static <T> T runAsPrivileged(final Callable<T> callable) throws Exception { public static <T> T runAsPrivileged(final Callable<T> callable) throws Exception {
return runAs(privilegedUser(), callable); createTenant(DEFAULT_TENANT);
return runAs(PRIVILEDGED_USER, callable);
} }
public static <T> T runAs(final WithUser withUser, final Callable<T> callable) throws Exception { public static <T> T runAs(final WithUser withUser, final Callable<T> callable) throws Exception {
@@ -82,7 +55,7 @@ public class WithSpringAuthorityRule implements BeforeEachCallback, AfterEachCal
private static void createTenant(final String tenantId) { private static void createTenant(final String tenantId) {
final SecurityContext oldContext = SecurityContextHolder.getContext(); final SecurityContext oldContext = SecurityContextHolder.getContext();
setSecurityContext(privilegedUser()); setSecurityContext(PRIVILEDGED_USER);
try { try {
SystemManagementHolder.getInstance().getSystemManagement().getTenantMetadata(tenantId); SystemManagementHolder.getInstance().getSystemManagement().getTenantMetadata(tenantId);
} finally { } finally {
@@ -102,10 +75,6 @@ public class WithSpringAuthorityRule implements BeforeEachCallback, AfterEachCal
return withUserAndTenant(principal, DEFAULT_TENANT, true, allSpPermision, false, authorities); 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) { public static WithUser withUserAndTenant(final String principal, final String tenant, final String... authorities) {
return withUserAndTenant(principal, tenant, true, true, false, authorities); return withUserAndTenant(principal, tenant, true, true, false, authorities);
} }
@@ -116,10 +85,6 @@ public class WithSpringAuthorityRule implements BeforeEachCallback, AfterEachCal
return createWithUser(principal, tenant, autoCreateTenant, allSpPermission, controller, authorities); 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, private static WithUser createWithUser(final String principal, final String tenant, final boolean autoCreateTenant,
final boolean allSpPermission, final boolean controller, final String... authorities) { final boolean allSpPermission, final boolean controller, final String... authorities) {
return new WithUser() { return new WithUser() {
@@ -171,12 +136,17 @@ public class WithSpringAuthorityRule implements BeforeEachCallback, AfterEachCal
}; };
} }
static class SecurityContextWithUser implements SecurityContext { static class WithUserSecurityContext implements SecurityContext {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final WithUser annotation; private final WithUser annotation;
public SecurityContextWithUser(WithUser annotation) { public WithUserSecurityContext(final WithUser annotation) {
this.annotation = annotation; this.annotation = annotation;
if (annotation.autoCreateTenant()) {
createTenant(annotation.tenantId());
}
} }
@Override @Override
@@ -214,7 +184,7 @@ public class WithSpringAuthorityRule implements BeforeEachCallback, AfterEachCal
@Override @Override
public boolean equals(final Object obj) { public boolean equals(final Object obj) {
if (obj instanceof SecurityContextWithUser otherSecurityContextWithUser) { if (obj instanceof WithUserSecurityContext otherSecurityContextWithUser) {
return Objects.equals(annotation, otherSecurityContextWithUser.annotation); return Objects.equals(annotation, otherSecurityContextWithUser.annotation);
} else { } else {
return false; return false;

View File

@@ -83,7 +83,7 @@ public @interface WithUser {
class WithUserPrincipalSecurityContextFactory implements WithSecurityContextFactory<WithUser> { class WithUserPrincipalSecurityContextFactory implements WithSecurityContextFactory<WithUser> {
@Override @Override
public SecurityContext createSecurityContext(final WithUser withUserPrincipal) { public SecurityContext createSecurityContext(final WithUser withUserPrincipal) {
return new WithSpringAuthorityRule.SecurityContextWithUser(withUserPrincipal); return new SecurityContextSwitch.WithUserSecurityContext(withUserPrincipal);
} }
} }
} }

View File

@@ -56,7 +56,7 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; 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.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
@@ -150,7 +150,7 @@ class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
// make a poll, audit information should not be changed, run as // make a poll, audit information should not be changed, run as
// controller principal! // 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)) mvc.perform(get(CONTROLLER_BASE, tenantAware.getCurrentTenant(), knownTargetControllerId))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -208,14 +208,14 @@ class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
@Expect(type = TargetPollEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1),
@Expect(type = TenantConfigurationCreatedEvent.class, count = 1) }) @Expect(type = TenantConfigurationCreatedEvent.class, count = 1) })
void pollWithModifiedGlobalPollingTime() throws Exception { 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, tenantConfigurationManagement.addOrUpdateConfiguration(TenantConfigurationKey.POLLING_TIME_INTERVAL,
"00:02:00"); "00:02:00");
return null; 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()) mvc.perform(get(CONTROLLER_BASE, tenantAware.getCurrentTenant(), 4711)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(content().contentType(MediaTypes.HAL_JSON)) .andExpect(status().isOk()).andExpect(content().contentType(MediaTypes.HAL_JSON))
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:02:00"))); .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:02:00")));
@@ -343,7 +343,7 @@ class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
final long create = System.currentTimeMillis(); final long create = System.currentTimeMillis();
// make a poll, audit information should be set on plug and play // 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)) mvc.perform(get(CONTROLLER_BASE, tenantAware.getCurrentTenant(), knownControllerId1))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -594,7 +594,7 @@ class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
void sleepTimeResponseForDifferentMaintenanceWindowParameters() throws Exception { void sleepTimeResponseForDifferentMaintenanceWindowParameters() throws Exception {
final DistributionSet ds = testdataFactory.createDistributionSet(""); 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, tenantConfigurationManagement.addOrUpdateConfiguration(TenantConfigurationKey.POLLING_TIME_INTERVAL,
"00:05:00"); "00:05:00");

View File

@@ -19,10 +19,8 @@ import org.eclipse.hawkbit.repository.test.matcher.EventVerifier;
import org.eclipse.hawkbit.repository.test.util.CleanupTestExecutionListener; import org.eclipse.hawkbit.repository.test.util.CleanupTestExecutionListener;
import org.eclipse.hawkbit.repository.test.util.JUnitTestLoggerExtension; import org.eclipse.hawkbit.repository.test.util.JUnitTestLoggerExtension;
import org.eclipse.hawkbit.repository.test.util.SharedSqlTestDatabaseExtension; 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.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.RestConfiguration; 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.FilterHttpResponse;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -46,8 +44,6 @@ import org.springframework.util.Base64Utils;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter; 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.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

View File

@@ -52,7 +52,7 @@ import org.eclipse.hawkbit.repository.model.RolloutGroupConditionBuilder;
import org.eclipse.hawkbit.repository.model.RolloutGroupConditions; import org.eclipse.hawkbit.repository.model.RolloutGroupConditions;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.test.util.RolloutTestApprovalStrategy; 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.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
@@ -1206,7 +1206,7 @@ class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTest {
private void awaitRunningState(final Long rolloutId) { private void awaitRunningState(final Long rolloutId) {
Awaitility.await().atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofMillis(100)).with() Awaitility.await().atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofMillis(100)).with()
.until(() -> WithSpringAuthorityRule .until(() -> SecurityContextSwitch
.runAsPrivileged( .runAsPrivileged(
() -> rolloutManagement.get(rolloutId).orElseThrow(NoSuchElementException::new)) () -> rolloutManagement.get(rolloutId).orElseThrow(NoSuchElementException::new))
.getStatus().equals(RolloutStatus.RUNNING)); .getStatus().equals(RolloutStatus.RUNNING));