Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[backend] Refactored TagRule to use AssetGRoup instead of Assets Issue/1998 #2170

Merged
merged 12 commits into from
Jan 9, 2025
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package io.openbas.migration;

import java.sql.Connection;
import java.sql.Statement;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.springframework.stereotype.Component;

@Component
public class V3_58__TagRule_Update extends BaseJavaMigration {

@Override
public void migrate(Context context) throws Exception {
Connection connection = context.getConnection();
Statement select = connection.createStatement();
select.execute(
"""
CREATE TABLE tag_rule_asset_groups (
tag_rule_id varchar(255) not null
constraint tag_rule_id_fk
references tag_rules,
asset_group_id varchar(255) not null
constraint asset_group_id_fk
references asset_groups
on delete cascade,
primary key (tag_rule_id, asset_group_id)
);
""");

select.execute(
"""
DROP TABLE IF EXISTS tag_rule_assets
""");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ public Iterable<Team> removeTeams(
}

/**
* Update the simulation and each of the injects to add/remove default assets
* Update the simulation and each of the injects to add/remove default asset groups
*
* @param exercise
* @param currentTags list of the tags before the update
Expand All @@ -630,29 +630,29 @@ public Iterable<Team> removeTeams(
public Exercise updateExercice(
@NotNull final Exercise exercise, @NotNull final Set<Tag> currentTags, boolean applyRule) {
if (applyRule) {
// Get assets from the TagRule of the added tags
List<Asset> defaultAssetsToAdd =
tagRuleService.getAssetsFromTagIds(
// Get asset groups from the TagRule of the added tags
List<AssetGroup> defaultAssetGroupsToAdd =
tagRuleService.getAssetGroupsFromTagIds(
exercise.getTags().stream()
.filter(tag -> !currentTags.contains(tag))
.map(Tag::getId)
.toList());

// Get assets from the TagRule of the removed tags
List<Asset> defaultAssetsToRemove =
tagRuleService.getAssetsFromTagIds(
// Get asset groups from the TagRule of the removed tags
List<AssetGroup> defaultAssetGroupsToRemove =
tagRuleService.getAssetGroupsFromTagIds(
currentTags.stream()
.filter(tag -> !exercise.getTags().contains(tag))
.map(Tag::getId)
.toList());

// Add/remove the default assets to/from the injects
// Add/remove the default asset groups to/from the injects
exercise
.getInjects()
.forEach(
inject ->
injectService.applyDefaultAssetsToInject(
inject.getId(), defaultAssetsToAdd, defaultAssetsToRemove));
injectService.applyDefaultAssetGroupsToInject(
inject.getId(), defaultAssetGroupsToAdd, defaultAssetGroupsToRemove));
}
exercise.setUpdatedAt(now());
return exerciseRepository.save(exercise);
Expand Down
16 changes: 8 additions & 8 deletions openbas-api/src/main/java/io/openbas/rest/inject/InjectApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -342,14 +342,14 @@ public Inject createInjectForExercise(
.toList());
}
inject.setTeams(fromIterable(teamRepository.findAllById(input.getTeams())));
inject.setAssets(fromIterable(assetService.assets(input.getAssets())));

// add default assets
inject.setAssets(
// add default asset groups
inject.setAssetGroups(
this.tagRuleService.applyTagRuleToInjectCreation(
exercise.getTags().stream().map(Tag::getId).toList(),
assetService.assets(input.getAssets())));
assetGroupService.assetGroups(input.getAssetGroups())));

inject.setAssetGroups(fromIterable(assetGroupService.assetGroups(input.getAssetGroups())));
inject.setTags(iterableToSet(tagRepository.findAllById(input.getTagIds())));
List<InjectDocument> injectDocuments =
input.getDocuments().stream()
Expand Down Expand Up @@ -582,14 +582,14 @@ public Inject createInjectForScenario(
.toList());
}
inject.setTeams(fromIterable(teamRepository.findAllById(input.getTeams())));
inject.setAssets(fromIterable(assetService.assets(input.getAssets())));

// add default assets
inject.setAssets(
// add default asset groups
inject.setAssetGroups(
this.tagRuleService.applyTagRuleToInjectCreation(
scenario.getTags().stream().map(Tag::getId).toList(),
assetService.assets(input.getAssets())));
assetGroupService.assetGroups(input.getAssetGroups())));

inject.setAssetGroups(fromIterable(assetGroupService.assetGroups(input.getAssetGroups())));
inject.setTags(iterableToSet(tagRepository.findAllById(input.getTagIds())));
List<InjectDocument> injectDocuments =
input.getDocuments().stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,42 +165,42 @@ public void delete(String id) {
}

/**
* Update an inject with default assets
* Update an inject with default asset groups
*
* @param injectId
* @param defaultAssetsToAdd
* @param defaultAssetsToRemove
* @param defaultAssetGroupsToAdd
* @param defaultAssetGroupsToRemove
* @return
*/
@Transactional
public Inject applyDefaultAssetsToInject(
public Inject applyDefaultAssetGroupsToInject(
final String injectId,
final List<Asset> defaultAssetsToAdd,
final List<Asset> defaultAssetsToRemove) {
final List<AssetGroup> defaultAssetGroupsToAdd,
final List<AssetGroup> defaultAssetGroupsToRemove) {

// fetch the inject
Inject inject =
this.injectRepository.findById(injectId).orElseThrow(ElementNotFoundException::new);

// remove/add default assets and remove duplicates
List<Asset> currentAssets = inject.getAssets();
// Get the Id of the assets to remove and filter the assets that are in both lists
List<String> assetIdsToRemove =
defaultAssetsToRemove.stream()
.filter(asset -> !defaultAssetsToAdd.contains(asset))
.map(Asset::getId)
// remove/add default asset groups and remove duplicates
List<AssetGroup> currentAssetGroups = inject.getAssetGroups();
// Get the Id of the asset groups to remove and filter the assets that are in both lists
List<String> assetGroupIdsToRemove =
defaultAssetGroupsToRemove.stream()
.filter(assetGroup -> !defaultAssetGroupsToAdd.contains(assetGroup))
.map(AssetGroup::getId)
savacano28 marked this conversation as resolved.
Show resolved Hide resolved
.toList();
Set<String> uniqueAssetsIds = new HashSet<>();
List<Asset> newListOfAssets =
Stream.concat(currentAssets.stream(), defaultAssetsToAdd.stream())
.filter(asset -> !assetIdsToRemove.contains(asset.getId()))
.filter(asset -> uniqueAssetsIds.add(asset.getId()))
Set<String> uniqueAssetGroupIds = new HashSet<>();
List<AssetGroup> newListOfAssetGroups =
Stream.concat(currentAssetGroups.stream(), defaultAssetGroupsToAdd.stream())
.filter(assetGroup -> !assetGroupIdsToRemove.contains(assetGroup.getId()))
.filter(assetGroup -> uniqueAssetGroupIds.add(assetGroup.getId()))
.collect(Collectors.toList());

if (new HashSet<>(currentAssets).equals(new HashSet<>(newListOfAssets))) {
if (new HashSet<>(currentAssetGroups).equals(new HashSet<>(newListOfAssetGroups))) {
return inject;
} else {
inject.setAssets(newListOfAssets);
inject.setAssetGroups(newListOfAssetGroups);
return this.injectRepository.save(inject);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,32 +66,32 @@ public void deleteTagRule(@PathVariable @NotBlank final String tagRuleId) {
@LogExecutionTime
@PostMapping(TagRuleApi.TAG_RULE_URI)
@Transactional(rollbackFor = Exception.class)
@Operation(summary = "Create TagRule", description = "Tag and assets needs to exists")
@Operation(summary = "Create TagRule", description = "Tag and Asset Groups needs to exists")
@ApiResponses(
value = {
@ApiResponse(responseCode = "200", description = "TagRule created"),
@ApiResponse(responseCode = "404", description = "Tag or Asset not found")
@ApiResponse(responseCode = "404", description = "Tag or Asset Group not found")
})
public TagRuleOutput createTagRule(@Valid @RequestBody final TagRuleInput input) {
return tagRuleMapper.toTagRuleOutput(
tagRuleService.createTagRule(input.getTagName(), input.getAssets()));
tagRuleService.createTagRule(input.getTagName(), input.getAssetGroups()));
}

@Secured(ROLE_ADMIN)
@LogExecutionTime
@PutMapping(TagRuleApi.TAG_RULE_URI + "/{tagRuleId}")
@Transactional(rollbackFor = Exception.class)
@Operation(summary = "Update TagRule", description = "Tag and assets needs to exists")
@Operation(summary = "Update TagRule", description = "Tag and Asset Groups needs to exists")
@ApiResponses(
value = {
@ApiResponse(responseCode = "200", description = "TagRule updated"),
@ApiResponse(responseCode = "404", description = "TagRule, Tag or Asset not found")
@ApiResponse(responseCode = "404", description = "TagRule, Tag or Asset Group not found")
})
public TagRuleOutput updateTagRule(
@PathVariable @NotBlank final String tagRuleId,
@Valid @RequestBody final TagRuleInput input) {
return tagRuleMapper.toTagRuleOutput(
tagRuleService.updateTagRule(tagRuleId, input.getTagName(), input.getAssets()));
tagRuleService.updateTagRule(tagRuleId, input.getTagName(), input.getAssetGroups()));
}

@LogExecutionTime
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ public class TagRuleInput {
@JsonProperty("tag_name")
private String tagName;

@JsonProperty("tag_rule_assets")
private List<String> assets = new ArrayList<>();
@JsonProperty("asset_groups")
private List<String> assetGroups = new ArrayList<>();
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package io.openbas.rest.tag_rule.form;

import io.openbas.database.model.Asset;
import io.openbas.database.model.AssetGroup;
import io.openbas.database.model.TagRule;
import java.util.stream.Collectors;
import org.springframework.stereotype.Component;
Expand All @@ -11,8 +11,9 @@ public TagRuleOutput toTagRuleOutput(final TagRule tagRule) {
return TagRuleOutput.builder()
.id(tagRule.getId())
.tagName(tagRule.getTag().getName())
.assets(
tagRule.getAssets().stream().collect(Collectors.toMap(Asset::getId, Asset::getName)))
.assetGroups(
tagRule.getAssetGroups().stream()
.collect(Collectors.toMap(AssetGroup::getId, AssetGroup::getName)))
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ public class TagRuleOutput {
@JsonProperty("tag_name")
private String tagName;

@JsonProperty("tag_rule_assets")
Map<String, String> assets = new HashMap<>();
@JsonProperty("asset_groups")
Map<String, String> assetGroups = new HashMap<>();
}
20 changes: 10 additions & 10 deletions openbas-api/src/main/java/io/openbas/service/ScenarioService.java
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ public Scenario updateScenario(@NotNull final Scenario scenario) {
}

/**
* Update the scenario and each of the injects to add/remove default assets
* Update the scenario and each of the injects to add/remove default asset groups
*
* @param scenario
* @param currentTags list of the tags before the update
Expand All @@ -308,29 +308,29 @@ public Scenario updateScenario(@NotNull final Scenario scenario) {
public Scenario updateScenario(
@NotNull final Scenario scenario, Set<Tag> currentTags, boolean applyRule) {
if (applyRule) {
// Get assets from the TagRule of the added tags
List<Asset> defaultAssetsToAdd =
tagRuleService.getAssetsFromTagIds(
// Get asset groups from the TagRule of the added tags
List<AssetGroup> defaultAssetGroupsToAdd =
tagRuleService.getAssetGroupsFromTagIds(
scenario.getTags().stream()
.filter(tag -> !currentTags.contains(tag))
.map(Tag::getId)
.toList());

// Get assets from the TagRule of the removed tags
List<Asset> defaultAssetsToRemove =
tagRuleService.getAssetsFromTagIds(
// Get asset groups from the TagRule of the removed tags
List<AssetGroup> defaultAssetGroupsToRemove =
tagRuleService.getAssetGroupsFromTagIds(
currentTags.stream()
.filter(tag -> !scenario.getTags().contains(tag))
.map(Tag::getId)
.toList());

// Add/remove the default assets to/from the injects
// Add/remove the default asset groups to/from the injects
scenario
.getInjects()
.forEach(
inject ->
injectService.applyDefaultAssetsToInject(
inject.getId(), defaultAssetsToAdd, defaultAssetsToRemove));
injectService.applyDefaultAssetGroupsToInject(
inject.getId(), defaultAssetGroupsToAdd, defaultAssetGroupsToRemove));
}
scenario.setUpdatedAt(now());
return this.scenarioRepository.save(scenario);
Expand Down
Loading
Loading