Sonar Fixes (10) (#2222)

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2025-01-23 16:48:24 +02:00
committed by GitHub
parent a0d149cc1d
commit fbaa352f7f
11 changed files with 172 additions and 145 deletions

View File

@@ -102,28 +102,42 @@ public class DdiRootController implements DdiRootControllerRestApi {
* File suffix for MDH hash download (see Linux md5sum). * File suffix for MDH hash download (see Linux md5sum).
*/ */
private static final String ARTIFACT_MD5_DWNL_SUFFIX = ".MD5SUM"; private static final String ARTIFACT_MD5_DWNL_SUFFIX = ".MD5SUM";
@Autowired
private ConfirmationManagement confirmationManagement; private final ControllerManagement controllerManagement;
@Autowired private final ConfirmationManagement confirmationManagement;
private ApplicationEventPublisher eventPublisher; private final ArtifactManagement artifactManagement;
@Autowired(required = false) private final ArtifactUrlHandler artifactUrlHandler;
private final SystemManagement systemManagement;
private final ApplicationEventPublisher eventPublisher;
private final BusProperties bus;
private final HawkbitSecurityProperties securityProperties;
private final TenantAware tenantAware;
private final EntityFactory entityFactory;
private ServiceMatcher serviceMatcher; private ServiceMatcher serviceMatcher;
@Autowired
private BusProperties bus; @SuppressWarnings("java:S107")
@Autowired public DdiRootController(
private ControllerManagement controllerManagement; final ControllerManagement controllerManagement, final ConfirmationManagement confirmationManagement,
@Autowired final ArtifactManagement artifactManagement, final ArtifactUrlHandler artifactUrlHandler,
private ArtifactManagement artifactManagement; final SystemManagement systemManagement,
@Autowired final ApplicationEventPublisher eventPublisher, final BusProperties bus,
private HawkbitSecurityProperties securityProperties; final HawkbitSecurityProperties securityProperties, final TenantAware tenantAware, final EntityFactory entityFactory) {
@Autowired this.controllerManagement = controllerManagement;
private TenantAware tenantAware; this.confirmationManagement = confirmationManagement;
@Autowired this.artifactManagement = artifactManagement;
private SystemManagement systemManagement; this.artifactUrlHandler = artifactUrlHandler;
@Autowired this.systemManagement = systemManagement;
private ArtifactUrlHandler artifactUrlHandler; this.eventPublisher = eventPublisher;
@Autowired this.bus = bus;
private EntityFactory entityFactory; this.securityProperties = securityProperties;
this.tenantAware = tenantAware;
this.entityFactory = entityFactory;
}
@Autowired(required = false)
public void setServiceMatcher(final ServiceMatcher serviceMatcher) {
this.serviceMatcher = serviceMatcher;
}
@Override @Override
public ResponseEntity<List<DdiArtifact>> getSoftwareModulesArtifacts( public ResponseEntity<List<DdiArtifact>> getSoftwareModulesArtifacts(

View File

@@ -114,6 +114,7 @@ public class AmqpMessageDispatcherService extends BaseAmqpService {
* @param distributionSetManagement to retrieve modules * @param distributionSetManagement to retrieve modules
* @param tenantConfigurationManagement to access tenant configuration * @param tenantConfigurationManagement to access tenant configuration
*/ */
@SuppressWarnings("java:S107")
protected AmqpMessageDispatcherService( protected AmqpMessageDispatcherService(
final RabbitTemplate rabbitTemplate, final RabbitTemplate rabbitTemplate,
final AmqpMessageSenderService amqpSenderService, final ArtifactUrlHandler artifactUrlHandler, final AmqpMessageSenderService amqpSenderService, final ArtifactUrlHandler artifactUrlHandler,

View File

@@ -24,28 +24,27 @@ import org.springframework.util.ErrorHandler;
@Story("Delegating Conditional Error Handler") @Story("Delegating Conditional Error Handler")
class DelegatingAmqpErrorHandlerTest { class DelegatingAmqpErrorHandlerTest {
private final DelegatingConditionalErrorHandler delegatingConditionalErrorHandler =
new DelegatingConditionalErrorHandler(
List.of(new IllegalArgumentExceptionHandler(), new IndexOutOfBoundsExceptionHandler()),
new DefaultErrorHandler());
@Test @Test
@Description("Verifies that with a list of conditional error handlers, the error is delegated to specific handler.") @Description("Verifies that with a list of conditional error handlers, the error is delegated to specific handler.")
void verifyDelegationHandling() { void verifyDelegationHandling() {
List<AmqpErrorHandler> handlers = new ArrayList<>(); final Throwable error = new Throwable(new IllegalArgumentException());
handlers.add(new IllegalArgumentExceptionHandler());
handlers.add(new IndexOutOfBoundsExceptionHandler());
assertThatExceptionOfType(IllegalArgumentException.class) assertThatExceptionOfType(IllegalArgumentException.class)
.as("Expected handled exception to be of type IllegalArgumentException") .as("Expected handled exception to be of type IllegalArgumentException")
.isThrownBy(() -> new DelegatingConditionalErrorHandler(handlers, new DefaultErrorHandler()) .isThrownBy(() -> delegatingConditionalErrorHandler.handleError(error));
.handleError(new Throwable(new IllegalArgumentException())));
} }
@Test @Test
@Description("Verifies that default handler is used if no handlers are defined for the specific exception.") @Description("Verifies that default handler is used if no handlers are defined for the specific exception.")
void verifyDefaultDelegationHandling() { void verifyDefaultDelegationHandling() {
List<AmqpErrorHandler> handlers = new ArrayList<>(); final Throwable error = new Throwable(new NullPointerException());
handlers.add(new IllegalArgumentExceptionHandler());
handlers.add(new IndexOutOfBoundsExceptionHandler());
assertThatExceptionOfType(RuntimeException.class) assertThatExceptionOfType(RuntimeException.class)
.as("Expected handled exception to be of type RuntimeException") .as("Expected handled exception to be of type RuntimeException")
.isThrownBy(() -> new DelegatingConditionalErrorHandler(handlers, new DefaultErrorHandler()) .isThrownBy(() -> delegatingConditionalErrorHandler.handleError(error));
.handleError(new Throwable(new NullPointerException())));
} }
// Test class // Test class
@@ -82,4 +81,4 @@ class DelegatingAmqpErrorHandlerTest {
throw new RuntimeException(t); throw new RuntimeException(t);
} }
} }
} }

View File

@@ -64,28 +64,34 @@ public class DeprecatedMgmtResource implements DeprecatedMgmtRestApi {
// logger that logs usage of deprecated API // logger that logs usage of deprecated API
private static final Logger DEPRECATED_USAGE_LOGGER = LoggerFactory.getLogger("DEPRECATED_USAGE"); private static final Logger DEPRECATED_USAGE_LOGGER = LoggerFactory.getLogger("DEPRECATED_USAGE");
@Autowired private final DistributionSetRepository distributionSetRepository;
private DistributionSetRepository distributionSetRepository; private final DistributionSetTagManagement distributionSetTagManagement;
@Autowired private final DistributionSetManagement distributionSetManagement;
private DistributionSetTagManagement distributionSetTagManagement; private final TargetRepository targetRepository;
@Autowired private final TargetTagRepository targetTagRepository;
private DistributionSetManagement distributionSetManagement; private final TargetManagement targetManagement;
@Autowired private final TargetTagManagement targetTagManagement;
private TargetRepository targetRepository; private final PlatformTransactionManager txManager;
@Autowired private final EntityManager entityManager;
private TargetTagRepository targetTagRepository;
@Autowired
private TargetManagement targetManagement;
@Autowired
private TargetTagManagement targetTagManagement;
@Autowired
private PlatformTransactionManager txManager;
@Autowired
private EntityManager entityManager;
private final TenantConfigHelper tenantConfigHelper; private final TenantConfigHelper tenantConfigHelper;
DeprecatedMgmtResource(final SystemSecurityContext securityContext, final TenantConfigurationManagement configurationManagement) { @SuppressWarnings("squid:S107")
DeprecatedMgmtResource(
final DistributionSetRepository distributionSetRepository, final DistributionSetTagManagement distributionSetTagManagement,
final DistributionSetManagement distributionSetManagement,
final TargetRepository targetRepository, final TargetTagRepository targetTagRepository, final TargetManagement targetManagement,
final TargetTagManagement targetTagManagement,
final PlatformTransactionManager txManager, final EntityManager entityManager,
final SystemSecurityContext securityContext, final TenantConfigurationManagement configurationManagement) {
this.distributionSetRepository = distributionSetRepository;
this.distributionSetTagManagement = distributionSetTagManagement;
this.distributionSetManagement = distributionSetManagement;
this.targetRepository = targetRepository;
this.targetTagRepository = targetTagRepository;
this.targetManagement = targetManagement;
this.targetTagManagement = targetTagManagement;
this.txManager = txManager;
this.entityManager = entityManager;
tenantConfigHelper = TenantConfigHelper.usingContext(securityContext, configurationManagement); tenantConfigHelper = TenantConfigHelper.usingContext(securityContext, configurationManagement);
} }
@@ -180,12 +186,12 @@ public class DeprecatedMgmtResource implements DeprecatedMgmtRestApi {
result = new DistributionSetTagAssignmentResult(ids.size() - toBeChangedDSs.size(), result = new DistributionSetTagAssignmentResult(ids.size() - toBeChangedDSs.size(),
Collections.emptyList(), Collections.emptyList(),
Collections.unmodifiableList( Collections.unmodifiableList(
toBeChangedDSs.stream().map(distributionSetRepository::save).collect(Collectors.toList())), toBeChangedDSs.stream().map(distributionSetRepository::save).toList()),
distributionSetTag); distributionSetTag);
} else { } else {
result = new DistributionSetTagAssignmentResult(ids.size() - toBeChangedDSs.size(), result = new DistributionSetTagAssignmentResult(ids.size() - toBeChangedDSs.size(),
Collections.unmodifiableList( Collections.unmodifiableList(
toBeChangedDSs.stream().map(distributionSetRepository::save).collect(Collectors.toList())), toBeChangedDSs.stream().map(distributionSetRepository::save).toList()),
Collections.emptyList(), distributionSetTag); Collections.emptyList(), distributionSetTag);
} }
return result; return result;
@@ -247,7 +253,7 @@ public class DeprecatedMgmtResource implements DeprecatedMgmtRestApi {
private static List<Long> findDistributionSetIds( private static List<Long> findDistributionSetIds(
final List<MgmtAssignedDistributionSetRequestBody> assignedDistributionSetRequestBodies) { final List<MgmtAssignedDistributionSetRequestBody> assignedDistributionSetRequestBodies) {
return assignedDistributionSetRequestBodies.stream() return assignedDistributionSetRequestBodies.stream()
.map(MgmtAssignedDistributionSetRequestBody::getDistributionSetId).collect(Collectors.toList()); .map(MgmtAssignedDistributionSetRequestBody::getDistributionSetId).toList();
} }
private DistributionSetTag findDistributionTagById(final Long distributionsetTagId) { private DistributionSetTag findDistributionTagById(final Long distributionsetTagId) {
@@ -257,7 +263,6 @@ public class DeprecatedMgmtResource implements DeprecatedMgmtRestApi {
private List<String> findTargetControllerIds( private List<String> findTargetControllerIds(
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) { final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
return assignedTargetRequestBodies.stream().map(MgmtAssignedTargetRequestBody::getControllerId) return assignedTargetRequestBodies.stream().map(MgmtAssignedTargetRequestBody::getControllerId).toList();
.collect(Collectors.toList());
} }
} }

View File

@@ -37,16 +37,17 @@ import org.springframework.web.bind.annotation.RequestBody;
/** /**
* REST Resource handling for DistributionSetTag CRUD operations. * REST Resource handling for DistributionSetTag CRUD operations.
*
* @deprecated since 0.6.0
*/ */
// no request mapping specified here to avoid CVE-2021-22044 in Feign client // no request mapping specified here to avoid CVE-2021-22044 in Feign client
@Deprecated(forRemoval = true) @Deprecated(forRemoval = true, since = "0.6.0")
@Tag(name = "Deprecated operations", description = "Deprecated REST operations.", @Tag(name = "Deprecated operations", description = "Deprecated REST operations.",
extensions = @Extension(name = OpenApiConfiguration.X_HAWKBIT, properties = @ExtensionProperty(name = "order", value = "2147483647"))) extensions = @Extension(name = OpenApiConfiguration.X_HAWKBIT, properties = @ExtensionProperty(name = "order", value = "2147483647")))
public interface DeprecatedMgmtRestApi { public interface DeprecatedMgmtRestApi {
/** /**
* Handles the POST request to toggle the assignment of distribution sets by * Handles the POST request to toggle the assignment of distribution sets by the given tag id.</br>
* the given tag id.</br>
* From {@link org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi} * From {@link org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi}
* *
* @param distributionsetTagId the ID of the distribution set tag to retrieve * @param distributionsetTagId the ID of the distribution set tag to retrieve

View File

@@ -67,11 +67,11 @@ public class ArtifactUpload {
* @param filename of the artifact * @param filename of the artifact
* @param providedSha1Sum optional sha1 checksum to check the new file against * @param providedSha1Sum optional sha1 checksum to check the new file against
* @param providedMd5Sum optional md5 checksum to check the new file against * @param providedMd5Sum optional md5 checksum to check the new file against
* @param overrideExisting to <code>true</code> if the artifact binary can be overridden * @param overrideExisting to <code>true</code> if the artifact binary can be overridden if it already exists
* if it already exists
* @param contentType the contentType of the file * @param contentType the contentType of the file
* @param filesize the size of the file in bytes. * @param filesize the size of the file in bytes.
*/ */
@SuppressWarnings("java:S107")
public ArtifactUpload(final InputStream inputStream, final long moduleId, final String filename, public ArtifactUpload(final InputStream inputStream, final long moduleId, final String filename,
final String providedMd5Sum, final String providedSha1Sum, final String providedSha256Sum, final String providedMd5Sum, final String providedSha1Sum, final String providedSha256Sum,
final boolean overrideExisting, final String contentType, final long filesize) { final boolean overrideExisting, final String contentType, final long filesize) {

View File

@@ -56,6 +56,7 @@ public class DeploymentRequest {
* with CONFIRMATION_FLOW active via tenant configuration) * with CONFIRMATION_FLOW active via tenant configuration)
* @throws InvalidMaintenanceScheduleException if the parameters do not define a valid maintenance schedule. * @throws InvalidMaintenanceScheduleException if the parameters do not define a valid maintenance schedule.
*/ */
@SuppressWarnings("java:S107")
public DeploymentRequest(final String controllerId, final Long distributionSetId, final ActionType actionType, public DeploymentRequest(final String controllerId, final Long distributionSetId, final ActionType actionType,
final long forceTime, final Integer weight, final String maintenanceSchedule, final long forceTime, final Integer weight, final String maintenanceSchedule,
final String maintenanceWindowDuration, final String maintenanceWindowTimeZone, final String maintenanceWindowDuration, final String maintenanceWindowTimeZone,

View File

@@ -16,8 +16,8 @@ import jakarta.validation.constraints.NotNull;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaBaseEntity_;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.repository.ActionRepository; import org.eclipse.hawkbit.repository.jpa.repository.ActionRepository;
@@ -59,7 +59,7 @@ public final class DeploymentHelper {
final JpaTarget target = (JpaTarget) action.getTarget(); final JpaTarget target = (JpaTarget) action.getTarget();
final List<Action> nextActiveActions = actionRepository final List<Action> nextActiveActions = actionRepository
.findAll(ActionSpecifications.byTargetIdAndIsActive(target.getId()), Sort.by(Sort.Order.asc(JpaAction_.ID))) .findAll(ActionSpecifications.byTargetIdAndIsActive(target.getId()), Sort.by(Sort.Order.asc(AbstractJpaBaseEntity_.ID)))
.stream() .stream()
.filter(a -> !a.getId().equals(action.getId())) .filter(a -> !a.getId().equals(action.getId()))
.map(Action.class::cast) .map(Action.class::cast)

View File

@@ -35,7 +35,7 @@ import org.eclipse.hawkbit.repository.jpa.specifications.TargetSpecifications;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetFilter; import org.eclipse.hawkbit.repository.model.DistributionSetFilter;
import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.MetaData;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -68,53 +68,53 @@ class DistributionSetAccessControllerTest extends AbstractAccessControllerTest {
TargetSpecifications.hasId(permittedAction.getTarget().getId()), TargetSpecifications.hasId(permittedAction.getTarget().getId()),
target -> target.getId().equals(permittedAction.getTarget().getId())); target -> target.getId().equals(permittedAction.getTarget().getId()));
final Long permittedActionId = permitted.getId();
// verify distributionSetManagement#findAll // verify distributionSetManagement#findAll
assertThat(distributionSetManagement.findAll(Pageable.unpaged()).get().map(Identifiable::getId).toList()) assertThat(distributionSetManagement.findAll(Pageable.unpaged()).get().map(Identifiable::getId).toList())
.containsOnly(permitted.getId()); .containsOnly(permittedActionId);
// verify distributionSetManagement#findByRsql // verify distributionSetManagement#findByRsql
assertThat(distributionSetManagement.findByRsql("name==*", Pageable.unpaged()).get().map(Identifiable::getId) assertThat(distributionSetManagement.findByRsql("name==*", Pageable.unpaged()).get().map(Identifiable::getId)
.toList()).containsOnly(permitted.getId()); .toList()).containsOnly(permittedActionId);
// verify distributionSetManagement#findByCompleted // verify distributionSetManagement#findByCompleted
assertThat(distributionSetManagement.findByCompleted(Pageable.unpaged(), true).get().map(Identifiable::getId) assertThat(distributionSetManagement.findByCompleted(Pageable.unpaged(), true).get().map(Identifiable::getId)
.toList()).containsOnly(permitted.getId()); .toList()).containsOnly(permittedActionId);
// verify distributionSetManagement#findByDistributionSetFilter // verify distributionSetManagement#findByDistributionSetFilter
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findByDistributionSetFilter(DistributionSetFilter.builder().isDeleted(false).build(), Pageable.unpaged() .findByDistributionSetFilter(DistributionSetFilter.builder().isDeleted(false).build(), Pageable.unpaged())
) .get().map(Identifiable::getId).toList()).containsOnly(permittedActionId);
.get().map(Identifiable::getId).toList()).containsOnly(permitted.getId());
// verify distributionSetManagement#get // verify distributionSetManagement#get
assertThat(distributionSetManagement.get(permitted.getId())).isPresent(); assertThat(distributionSetManagement.get(permittedActionId)).isPresent();
assertThat(distributionSetManagement.get(hidden.getId())).isEmpty(); final Long hiddenId = hidden.getId();
assertThat(distributionSetManagement.get(hiddenId)).isEmpty();
// verify distributionSetManagement#getWithDetails // verify distributionSetManagement#getWithDetails
assertThat(distributionSetManagement.getWithDetails(permitted.getId())).isPresent(); assertThat(distributionSetManagement.getWithDetails(permittedActionId)).isPresent();
assertThat(distributionSetManagement.getWithDetails(hidden.getId())).isEmpty(); assertThat(distributionSetManagement.getWithDetails(hiddenId)).isEmpty();
// verify distributionSetManagement#get // verify distributionSetManagement#get
assertThat(distributionSetManagement.getValid(permitted.getId()).getId()).isEqualTo(permitted.getId()); assertThat(distributionSetManagement.getValid(permittedActionId).getId()).isEqualTo(permittedActionId);
assertThatThrownBy(() -> { assertThatThrownBy(() -> distributionSetManagement.getValid(hiddenId))
assertThat(distributionSetManagement.getValid(hidden.getId())); .as("Distribution set should not be found.").isInstanceOf(EntityNotFoundException.class);
}).as("Distribution set should not be found.").isInstanceOf(EntityNotFoundException.class);
// verify distributionSetManagement#get // verify distributionSetManagement#get
assertThatThrownBy(() -> { final List<Long> allActionIds = Arrays.asList(permittedActionId, hiddenId);
distributionSetManagement.get(Arrays.asList(permitted.getId(), hidden.getId())); assertThatThrownBy(() -> distributionSetManagement.get(allActionIds))
}).as("Fail if request hidden.").isInstanceOf(EntityNotFoundException.class); .as("Fail if request hidden.").isInstanceOf(EntityNotFoundException.class);
// verify distributionSetManagement#getByNameAndVersion // verify distributionSetManagement#getByNameAndVersion
assertThat(distributionSetManagement.findByNameAndVersion(permitted.getName(), permitted.getVersion())) assertThat(distributionSetManagement.findByNameAndVersion(permitted.getName(), permitted.getVersion())).isPresent();
.isPresent();
assertThat(distributionSetManagement.findByNameAndVersion(hidden.getName(), hidden.getVersion())).isEmpty(); assertThat(distributionSetManagement.findByNameAndVersion(hidden.getName(), hidden.getVersion())).isEmpty();
// verify distributionSetManagement#getByAction // verify distributionSetManagement#getByAction
assertThat(distributionSetManagement.findByAction(permittedAction.getId())).isPresent(); assertThat(distributionSetManagement.findByAction(permittedAction.getId())).isPresent();
assertThatThrownBy(() -> { final Long hiddenActionId = hiddenAction.getId();
distributionSetManagement.findByAction(hiddenAction.getId()); assertThatThrownBy(() -> distributionSetManagement.findByAction(hiddenActionId))
}).as("Action is hidden.").isInstanceOf(InsufficientPermissionException.class); .as("Action is hidden.").isInstanceOf(InsufficientPermissionException.class);
} }
@Test @Test
@@ -140,41 +140,46 @@ class DistributionSetAccessControllerTest extends AbstractAccessControllerTest {
defineAccess(AccessController.Operation.UPDATE, permitted); defineAccess(AccessController.Operation.UPDATE, permitted);
// verify distributionSetManagement#assignSoftwareModules // verify distributionSetManagement#assignSoftwareModules
assertThat(distributionSetManagement.assignSoftwareModules(permitted.getId(), Collections.singletonList(swModule.getId()))) final var singleModuleIdList = Collections.singletonList(swModule.getId());
assertThat(distributionSetManagement.assignSoftwareModules(permitted.getId(), singleModuleIdList))
.satisfies(ds -> assertThat(ds.getModules().stream().map(Identifiable::getId).toList()).contains(swModule.getId())); .satisfies(ds -> assertThat(ds.getModules().stream().map(Identifiable::getId).toList()).contains(swModule.getId()));
assertThatThrownBy(() -> distributionSetManagement.assignSoftwareModules(readOnly.getId(), Collections.singletonList(swModule.getId()))) final Long readOnlyId = readOnly.getId();
assertThatThrownBy(() -> distributionSetManagement.assignSoftwareModules(readOnlyId, singleModuleIdList))
.as("Distribution set not allowed to me modified.") .as("Distribution set not allowed to me modified.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
assertThatThrownBy(() -> distributionSetManagement.assignSoftwareModules(hidden.getId(), Collections.singletonList(swModule.getId()))) final Long hiddenId = hidden.getId();
assertThatThrownBy(() -> distributionSetManagement.assignSoftwareModules(hiddenId, singleModuleIdList))
.as("Distribution set should not be visible.") .as("Distribution set should not be visible.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
final JpaDistributionSetMetadata metadata = new JpaDistributionSetMetadata("test", "test"); final JpaDistributionSetMetadata metadata = new JpaDistributionSetMetadata("test", "test");
// verify distributionSetManagement#createMetaData // verify distributionSetManagement#createMetaData
distributionSetManagement.putMetaData(permitted.getId(), Collections.singletonList(metadata)); final List<MetaData> metadataList = Collections.singletonList(metadata);
assertThatThrownBy(() -> distributionSetManagement.putMetaData(readOnly.getId(), Collections.singletonList(metadata))) distributionSetManagement.putMetaData(permitted.getId(), metadataList);
assertThatThrownBy(() -> distributionSetManagement.putMetaData(readOnlyId, metadataList))
.as("Distribution set not allowed to me modified.") .as("Distribution set not allowed to me modified.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
assertThatThrownBy(() -> distributionSetManagement.putMetaData(hidden.getId(), Collections.singletonList(metadata))) assertThatThrownBy(() -> distributionSetManagement.putMetaData(hiddenId, metadataList))
.as("Distribution set should not be visible.") .as("Distribution set should not be visible.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
// verify distributionSetManagement#updateMetaData // verify distributionSetManagement#updateMetaData
distributionSetManagement.updateMetaData(permitted.getId(), metadata); distributionSetManagement.updateMetaData(permitted.getId(), metadata);
assertThatThrownBy(() -> distributionSetManagement.updateMetaData(readOnly.getId(), metadata)) assertThatThrownBy(() -> distributionSetManagement.updateMetaData(readOnlyId, metadata))
.as("Distribution set not allowed to me modified.") .as("Distribution set not allowed to me modified.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
assertThatThrownBy(() -> distributionSetManagement.updateMetaData(hidden.getId(), metadata)) assertThatThrownBy(() -> distributionSetManagement.updateMetaData(hiddenId, metadata))
.as("Distribution set should not be visible.") .as("Distribution set should not be visible.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
// verify distributionSetManagement#deleteMetaData // verify distributionSetManagement#deleteMetaData
distributionSetManagement.deleteMetaData(permitted.getId(), metadata.getKey()); final String metadataKey = metadata.getKey();
assertThatThrownBy(() -> distributionSetManagement.deleteMetaData(readOnly.getId(), metadata.getKey())) distributionSetManagement.deleteMetaData(permitted.getId(), metadataKey);
assertThatThrownBy(() -> distributionSetManagement.deleteMetaData(readOnlyId, metadataKey))
.as("Distribution set not allowed to me modified.") .as("Distribution set not allowed to me modified.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
assertThatThrownBy(() -> distributionSetManagement.deleteMetaData(hidden.getId(), metadata.getKey())) assertThatThrownBy(() -> distributionSetManagement.deleteMetaData(hiddenId, metadataKey))
.as("Distribution set should not be visible.") .as("Distribution set should not be visible.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
} }
@@ -189,12 +194,12 @@ class DistributionSetAccessControllerTest extends AbstractAccessControllerTest {
final DistributionSet permitted = testdataFactory.createDistributionSet(); final DistributionSet permitted = testdataFactory.createDistributionSet();
final DistributionSet readOnly = testdataFactory.createDistributionSet(); final DistributionSet readOnly = testdataFactory.createDistributionSet();
final DistributionSet hidden = testdataFactory.createDistributionSet(); final DistributionSet hidden = testdataFactory.createDistributionSet();
final DistributionSetTag dsTag = distributionSetTagManagement.create(entityFactory.tag().create().name("dsTag")); final Long dsTagId = distributionSetTagManagement.create(entityFactory.tag().create().name("dsTag")).getId();
final DistributionSetTag dsTag2 = distributionSetTagManagement.create(entityFactory.tag().create().name("dsTag2")); final Long dsTag2Id = distributionSetTagManagement.create(entityFactory.tag().create().name("dsTag2")).getId();
// perform tag assignment before setting access rules // perform tag assignment before setting access rules
distributionSetManagement.assignTag(Arrays.asList(permitted.getId(), readOnly.getId(), hidden.getId()), distributionSetManagement.assignTag(Arrays.asList(permitted.getId(), readOnly.getId(), hidden.getId()),
dsTag.getId()); dsTagId);
// entities created - reset rules // entities created - reset rules
testAccessControlManger.deleteAllRules(); testAccessControlManger.deleteAllRules();
@@ -204,53 +209,55 @@ class DistributionSetAccessControllerTest extends AbstractAccessControllerTest {
// allow updating the permitted distributionSet // allow updating the permitted distributionSet
defineAccess(AccessController.Operation.UPDATE, permitted); defineAccess(AccessController.Operation.UPDATE, permitted);
assertThat(distributionSetManagement.findByTag(dsTag.getId(), Pageable.unpaged()).get().map(Identifiable::getId) assertThat(distributionSetManagement.findByTag(dsTagId, Pageable.unpaged()).get().map(Identifiable::getId)
.toList()).containsOnly(permitted.getId(), readOnly.getId()); .toList()).containsOnly(permitted.getId(), readOnly.getId());
assertThat(distributionSetManagement.findByRsqlAndTag("name==*", dsTag.getId(), Pageable.unpaged()).get() assertThat(distributionSetManagement.findByRsqlAndTag("name==*", dsTagId, Pageable.unpaged()).get()
.map(Identifiable::getId).toList()).containsOnly(permitted.getId(), readOnly.getId()); .map(Identifiable::getId).toList()).containsOnly(permitted.getId(), readOnly.getId());
// verify distributionSetManagement#unassignTag on permitted target // verify distributionSetManagement#unassignTag on permitted target
assertThat(distributionSetManagement assertThat(distributionSetManagement
.unassignTag(Collections.singletonList(permitted.getId()), dsTag.getId())) .unassignTag(Collections.singletonList(permitted.getId()), dsTagId))
.size() .size()
.isEqualTo(1); .isEqualTo(1);
// verify distributionSetManagement#assignTag on permitted target // verify distributionSetManagement#assignTag on permitted target
assertThat(distributionSetManagement.assignTag(Collections.singletonList(permitted.getId()), dsTag.getId())) assertThat(distributionSetManagement.assignTag(Collections.singletonList(permitted.getId()), dsTagId))
.hasSize(1); .hasSize(1);
// verify distributionSetManagement#unAssignTag on permitted target // verify distributionSetManagement#unAssignTag on permitted target
assertThat(distributionSetManagement.unassignTag(List.of(permitted.getId()), dsTag.getId()) assertThat(distributionSetManagement.unassignTag(List.of(permitted.getId()), dsTagId)
.get(0).getId()) .get(0).getId())
.isEqualTo(permitted.getId()); .isEqualTo(permitted.getId());
// assignment is denied for readOnlyTarget (read, but no update permissions) // assignment is denied for readOnlyTarget (read, but no update permissions)
final List<Long> readOblyList = Collections.singletonList(readOnly.getId());
assertThatThrownBy(() -> assertThatThrownBy(() ->
distributionSetManagement.unassignTag(Collections.singletonList(readOnly.getId()), dsTag.getId())) distributionSetManagement.unassignTag(readOblyList, dsTagId))
.as("Missing update permissions for target to toggle tag assignment.") .as("Missing update permissions for target to toggle tag assignment.")
.isInstanceOf(InsufficientPermissionException.class); .isInstanceOf(InsufficientPermissionException.class);
// assignment is denied for readOnlyTarget (read, but no update permissions) // assignment is denied for readOnlyTarget (read, but no update permissions)
// dsTag2- since - it is tagged with dsTag and won't do anything if assigning dsTag // dsTag2- since - it is tagged with dsTag and won't do anything if assigning dsTag
assertThatThrownBy(() -> { assertThatThrownBy(() -> {
distributionSetManagement.assignTag(Collections.singletonList(readOnly.getId()), dsTag2.getId()); distributionSetManagement.assignTag(readOblyList, dsTag2Id);
}).as("Missing update permissions for target to toggle tag assignment.") }).as("Missing update permissions for target to toggle tag assignment.")
.isInstanceOf(InsufficientPermissionException.class); .isInstanceOf(InsufficientPermissionException.class);
// assignment is denied for hiddenTarget since it's hidden // assignment is denied for hiddenTarget since it's hidden
assertThatThrownBy(() -> distributionSetManagement.unassignTag(Collections.singletonList(hidden.getId()), dsTag.getId())) final List<Long> hiddenList = Collections.singletonList(hidden.getId());
assertThatThrownBy(() -> distributionSetManagement.unassignTag(hiddenList, dsTagId))
.as("Missing update permissions for target to toggle tag assignment.") .as("Missing update permissions for target to toggle tag assignment.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
// assignment is denied for hiddenTarget since it's hidden // assignment is denied for hiddenTarget since it's hidden
assertThatThrownBy(() -> { assertThatThrownBy(() -> {
distributionSetManagement.assignTag(Collections.singletonList(hidden.getId()), dsTag.getId()); distributionSetManagement.assignTag(hiddenList, dsTagId);
}).as("Missing update permissions for target to toggle tag assignment.") }).as("Missing update permissions for target to toggle tag assignment.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
// assignment is denied for hiddenTarget since it's hidden // assignment is denied for hiddenTarget since it's hidden
assertThatThrownBy(() -> { final List<Long> hiddenIdList = List.of(hidden.getId());
distributionSetManagement.unassignTag(List.of(hidden.getId()), dsTag.getId()); assertThatThrownBy(() -> distributionSetManagement.unassignTag(hiddenIdList, dsTagId))
}).as("Missing update permissions for target to toggle tag assignment.") .as("Missing update permissions for target to toggle tag assignment.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
} }
@@ -287,12 +294,10 @@ class DistributionSetAccessControllerTest extends AbstractAccessControllerTest {
.updateAutoAssignDS(new AutoAssignDistributionSetUpdate(targetFilterQuery.getId()) .updateAutoAssignDS(new AutoAssignDistributionSetUpdate(targetFilterQuery.getId())
.ds(readOnly.getId()).actionType(Action.ActionType.FORCED).confirmationRequired(false)) .ds(readOnly.getId()).actionType(Action.ActionType.FORCED).confirmationRequired(false))
.getAutoAssignDistributionSet().getId(); .getAutoAssignDistributionSet().getId();
assertThatThrownBy(() -> { final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = new AutoAssignDistributionSetUpdate(targetFilterQuery.getId())
targetFilterQueryManagement .ds(hidden.getId()).actionType(Action.ActionType.FORCED).confirmationRequired(false);
.updateAutoAssignDS(new AutoAssignDistributionSetUpdate(targetFilterQuery.getId()) assertThatThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate))
.ds(hidden.getId()).actionType(Action.ActionType.FORCED).confirmationRequired(false)) .isInstanceOf(EntityNotFoundException.class);
.getAutoAssignDistributionSet().getId();
}).isInstanceOf(EntityNotFoundException.class);
} }
private void defineAccess(final AccessController.Operation operation, final DistributionSet... distributionSets) { private void defineAccess(final AccessController.Operation operation, final DistributionSet... distributionSets) {

View File

@@ -24,6 +24,7 @@ import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.stream.IntStream;
import java.util.stream.Stream; import java.util.stream.Stream;
import jakarta.validation.ConstraintViolationException; import jakarta.validation.ConstraintViolationException;
@@ -196,18 +197,19 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test verifies that the 'max actions per target' quota is enforced.") @Description("Test verifies that the 'max actions per target' quota is enforced.")
void assertMaxActionsPerTargetQuotaIsEnforced() { void assertMaxActionsPerTargetQuotaIsEnforced() {
enableMultiAssignments();
final int maxActions = quotaManagement.getMaxActionsPerTarget(); final int maxActions = quotaManagement.getMaxActionsPerTarget();
final Target testTarget = testdataFactory.createTarget(); final Target testTarget = testdataFactory.createTarget();
final DistributionSet ds1 = testdataFactory.createDistributionSet("ds1"); final Long ds1Id = testdataFactory.createDistributionSet("ds1").getId();
enableMultiAssignments(); final String controllerId = testTarget.getControllerId();
for (int i = 0; i < maxActions; i++) { for (int i = 0; i < maxActions; i++) {
deploymentManagement.offlineAssignedDistributionSets(Collections deploymentManagement.offlineAssignedDistributionSets(List.of(new SimpleEntry<>(controllerId, ds1Id)));
.singletonList(new SimpleEntry<>(testTarget.getControllerId(), ds1.getId())));
} }
assertThatExceptionOfType(AssignmentQuotaExceededException.class) assertThatExceptionOfType(AssignmentQuotaExceededException.class)
.isThrownBy(() -> assignDistributionSet(ds1.getId(), testTarget.getControllerId(), 77)); .isThrownBy(() -> assignDistributionSet(ds1Id, controllerId, 77));
} }
@Test @Test
@@ -277,10 +279,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// not exists // not exists
assignDS.add(100L); assignDS.add(100L);
final DistributionSetTag tag = distributionSetTagManagement.create(entityFactory.tag().create().name("Tag1")); final Long tagId = distributionSetTagManagement.create(entityFactory.tag().create().name("Tag1")).getId();
assertThatExceptionOfType(EntityNotFoundException.class) assertThatExceptionOfType(EntityNotFoundException.class)
.isThrownBy(() -> distributionSetManagement.assignTag(assignDS, tag.getId())) .isThrownBy(() -> distributionSetManagement.assignTag(assignDS, tagId))
.withMessageContaining("DistributionSet") .withMessageContaining("DistributionSet")
.withMessageContaining(String.valueOf(100L)); .withMessageContaining(String.valueOf(100L));
} }
@@ -455,7 +457,7 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final Target target = action.getTarget(); final Target target = action.getTarget();
final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true); final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true);
final Action assigningAction = assignSet(target, ds); final Long assigningActionId = assignSet(target, ds).getId();
// verify assignment // verify assignment
assertThat(actionRepository.findAll()).as("wrong size of action").hasSize(2); assertThat(actionRepository.findAll()).as("wrong size of action").hasSize(2);
@@ -464,7 +466,7 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// force quit assignment // force quit assignment
assertThatExceptionOfType(ForceQuitActionNotAllowedException.class) assertThatExceptionOfType(ForceQuitActionNotAllowedException.class)
.as("expected ForceQuitActionNotAllowedException") .as("expected ForceQuitActionNotAllowedException")
.isThrownBy(() -> deploymentManagement.forceQuitAction(assigningAction.getId())); .isThrownBy(() -> deploymentManagement.forceQuitAction(assigningActionId));
} }
@Test @Test
@@ -706,8 +708,9 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DeploymentRequest targetToDS1 = DeploymentManagement final DeploymentRequest targetToDS1 = DeploymentManagement
.deploymentRequest(target.getControllerId(), distributionSets.get(1).getId()).setWeight(565).build(); .deploymentRequest(target.getControllerId(), distributionSets.get(1).getId()).setWeight(565).build();
final List<DeploymentRequest> deploymentRequests = List.of(targetToDS0, targetToDS1);
Assertions.assertThatExceptionOfType(MultiAssignmentIsNotEnabledException.class) Assertions.assertThatExceptionOfType(MultiAssignmentIsNotEnabledException.class)
.isThrownBy(() -> deploymentManagement.assignDistributionSets(Arrays.asList(targetToDS0, targetToDS1))); .isThrownBy(() -> deploymentManagement.assignDistributionSets(deploymentRequests));
enableMultiAssignments(); enableMultiAssignments();
assertThat(getResultingActionCount( assertThat(getResultingActionCount(
@@ -981,16 +984,18 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DeploymentRequest weightTooHigh = DeploymentManagement.deploymentRequest(targetId, dsId) final DeploymentRequest weightTooHigh = DeploymentManagement.deploymentRequest(targetId, dsId)
.setWeight(Action.WEIGHT_MAX + 1).build(); .setWeight(Action.WEIGHT_MAX + 1).build();
enableMultiAssignments(); enableMultiAssignments();
final List<DeploymentRequest> deploymentRequestsTooLow = Collections.singletonList(weightTooLow);
Assertions.assertThatExceptionOfType(ConstraintViolationException.class) Assertions.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> deploymentManagement.assignDistributionSets(Collections.singletonList(weightTooLow))); .isThrownBy(() -> deploymentManagement.assignDistributionSets(deploymentRequestsTooLow));
final List<DeploymentRequest> deploymentRequestsTooHigh = Collections.singletonList(weightTooHigh);
Assertions.assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy( Assertions.assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(
() -> deploymentManagement.assignDistributionSets(Collections.singletonList(weightTooHigh))); () -> deploymentManagement.assignDistributionSets(deploymentRequestsTooHigh));
final Long valideActionId1 = getFirstAssignedAction( final Long validActionId1 = getFirstAssignedAction(
deploymentManagement.assignDistributionSets(Collections.singletonList(valideRequest1)).get(0)).getId(); deploymentManagement.assignDistributionSets(Collections.singletonList(valideRequest1)).get(0)).getId();
final Long valideActionId2 = getFirstAssignedAction( final Long validActionId2 = getFirstAssignedAction(
deploymentManagement.assignDistributionSets(Collections.singletonList(valideRequest2)).get(0)).getId(); deploymentManagement.assignDistributionSets(Collections.singletonList(valideRequest2)).get(0)).getId();
assertThat(actionRepository.findById(valideActionId1).get().getWeight()).get().isEqualTo(Action.WEIGHT_MAX); assertThat(actionRepository.findById(validActionId1).get().getWeight()).get().isEqualTo(Action.WEIGHT_MAX);
assertThat(actionRepository.findById(valideActionId2).get().getWeight()).get().isEqualTo(Action.WEIGHT_MIN); assertThat(actionRepository.findById(validActionId2).get().getWeight()).get().isEqualTo(Action.WEIGHT_MIN);
} }
/** /**
@@ -1283,10 +1288,9 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.asList(DistributionSetSpecification.isDeleted(true), DistributionSetSpecification.isCompleted(true))), .asList(DistributionSetSpecification.isDeleted(true), DistributionSetSpecification.isCompleted(true))),
PAGE).getContent()).as("wrong size of founded ds").hasSize(noOfDistributionSets); PAGE).getContent()).as("wrong size of founded ds").hasSize(noOfDistributionSets);
for (final DistributionSet ignored : deploymentResult.getDistributionSets()) { IntStream.range(0, deploymentResult.getDistributionSets().size()).forEach(i -> testdataFactory.sendUpdateActionStatusToTargets(
testdataFactory.sendUpdateActionStatusToTargets(deploymentResult.getDeployedTargets(), Status.FINISHED, deploymentResult.getDeployedTargets(), Status.FINISHED, Collections.singletonList("blabla alles gut")));
Collections.singletonList("blabla alles gut"));
}
// try to delete again // try to delete again
distributionSetManagement.delete(deploymentResult.getDistributionSetIDs()); distributionSetManagement.delete(deploymentResult.getDistributionSetIDs());
// verify that the result is the same, even though distributionSet dsA // verify that the result is the same, even though distributionSet dsA
@@ -1304,22 +1308,18 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Deletes multiple targets and verifies that all related metadata is also deleted.") @Description("Deletes multiple targets and verifies that all related metadata is also deleted.")
void deletesTargetsAndVerifyCascadeDeletes() { void deletesTargetsAndVerifyCascadeDeletes() {
final String undeployedTargetPrefix = "undep-T"; final String undeployedTargetPrefix = "undep-T";
final int noOfUndeployedTargets = 2; final int noOfUndeployedTargets = 2;
final String deployedTargetPrefix = "dep-T"; final String deployedTargetPrefix = "dep-T";
final int noOfDeployedTargets = 4; final int noOfDeployedTargets = 4;
final int noOfDistributionSets = 3; final int noOfDistributionSets = 3;
final DeploymentResult deploymentResult = prepareComplexRepo(undeployedTargetPrefix, noOfUndeployedTargets, final DeploymentResult deploymentResult = prepareComplexRepo(undeployedTargetPrefix, noOfUndeployedTargets,
deployedTargetPrefix, noOfDeployedTargets, noOfDistributionSets, "myTestDS"); deployedTargetPrefix, noOfDeployedTargets, noOfDistributionSets, "myTestDS");
for (final DistributionSet ignored : deploymentResult.getDistributionSets()) { IntStream.range(0, deploymentResult.getDistributionSets().size()).forEach(i -> testdataFactory.sendUpdateActionStatusToTargets(
testdataFactory.sendUpdateActionStatusToTargets(deploymentResult.getDeployedTargets(), Status.FINISHED, deploymentResult.getDeployedTargets(), Status.FINISHED, Collections.singletonList("blabla alles gut")));
Collections.singletonList("blabla alles gut"));
}
assertThat(targetManagement.count()).as("size of targets is wrong").isNotZero(); assertThat(targetManagement.count()).as("size of targets is wrong").isNotZero();
assertThat(actionStatusRepository.count()).as("size of action status is wrong").isNotZero(); assertThat(actionStatusRepository.count()).as("size of action status is wrong").isNotZero();

View File

@@ -69,6 +69,7 @@ public class DeviceApp {
private final DdiController device; private final DdiController device;
private final MgmtApi mgmtApi; private final MgmtApi mgmtApi;
@SuppressWarnings("java:S3358")
Shell(final DdiTenant ddiTenant, final MgmtApi mgmtApi, final Optional<UpdateHandler> updateHandler) { Shell(final DdiTenant ddiTenant, final MgmtApi mgmtApi, final Optional<UpdateHandler> updateHandler) {
this.ddiTenant = ddiTenant; this.ddiTenant = ddiTenant;
this.mgmtApi = mgmtApi; this.mgmtApi = mgmtApi;