Skip to content

Commit

Permalink
[backend] Avoid raising stack trace instead of returning a 404 (#867)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dimfacion authored May 22, 2024
1 parent cc7624c commit dfb6fa0
Show file tree
Hide file tree
Showing 33 changed files with 249 additions and 190 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package io.openbas.config;

import io.openbas.rest.exception.ElementNotFoundException;
import lombok.extern.java.Log;
import org.springdoc.api.ErrorMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Log
public class GlobalExceptionHandler {

@ExceptionHandler(ElementNotFoundException.class)
public ResponseEntity<ErrorMessage> handleElementNotFoundException() {
ErrorMessage message = new ErrorMessage("Not found");
return new ResponseEntity<ErrorMessage>(message, HttpStatus.NOT_FOUND);
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.openbas.helper;

import io.openbas.database.model.Base;
import io.openbas.rest.exception.ElementNotFoundException;
import org.springframework.data.repository.CrudRepository;

import java.util.Optional;
Expand Down Expand Up @@ -32,6 +33,6 @@ public static <T> T resolveOptionalRelation(String inputRelationId, CrudReposito
}

public static <T> T resolveRelation(String inputRelationId, CrudRepository<T, String> repository) {
return repository.findById(inputRelationId).orElseThrow();
return repository.findById(inputRelationId).orElseThrow(ElementNotFoundException::new);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import io.openbas.database.model.Inject;
import io.openbas.database.model.InjectExpectation;
import io.openbas.database.model.InjectStatus;
import io.openbas.inject_expectation.InjectExpectationService;
import io.openbas.rest.atomic_testing.form.AtomicTestingInput;
import io.openbas.rest.atomic_testing.form.AtomicTestingUpdateTagsInput;
import io.openbas.rest.atomic_testing.form.InjectResultDTO;
import io.openbas.rest.exception.ElementNotFoundException;
import io.openbas.rest.helper.RestBehavior;
import io.openbas.service.AtomicTestingService;
import io.openbas.utils.AtomicTestingMapper;
Expand Down Expand Up @@ -48,12 +48,12 @@ inject, getTargets(
public InjectResultDTO findAtomicTesting(@PathVariable String injectId) {
return atomicTestingService.findById(injectId)
.map(AtomicTestingMapper::toDtoWithTargetResults)
.orElseThrow();
.orElseThrow(ElementNotFoundException::new);
}

@GetMapping("/{injectId}/update")
public Inject findAtomicTestingForUpdate(@PathVariable String injectId) {
return atomicTestingService.findById(injectId).orElseThrow();
return atomicTestingService.findById(injectId).orElseThrow(ElementNotFoundException::new);
}

@PostMapping()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import io.openbas.rest.attack_pattern.form.AttackPatternCreateInput;
import io.openbas.rest.attack_pattern.form.AttackPatternUpdateInput;
import io.openbas.rest.attack_pattern.form.AttackPatternUpsertInput;
import io.openbas.rest.exception.ElementNotFoundException;
import io.openbas.rest.helper.RestBehavior;
import io.openbas.utils.pagination.SearchPaginationInput;
import jakarta.transaction.Transactional;
Expand Down Expand Up @@ -75,7 +76,7 @@ public Page<AttackPattern> attackPatterns(@RequestBody @Valid final SearchPagina

@GetMapping("/api/attack_patterns/{attackPatternId}")
public AttackPattern attackPattern(@PathVariable String attackPatternId) {
return attackPatternRepository.findById(attackPatternId).orElseThrow();
return attackPatternRepository.findById(attackPatternId).orElseThrow(ElementNotFoundException::new);
}

@Secured(ROLE_ADMIN)
Expand All @@ -90,7 +91,7 @@ public AttackPattern createAttackPattern(@Valid @RequestBody AttackPatternCreate

@GetMapping("/api/attack_patterns/{attackPatternId}/injector_contracts")
public Iterable<InjectorContract> injectorContracts(@PathVariable String attackPatternId) {
attackPatternRepository.findById(attackPatternId).orElseThrow();
attackPatternRepository.findById(attackPatternId).orElseThrow(ElementNotFoundException::new);
return injectorContractRepository.findAll(InjectorContractSpecification.fromAttackPattern(attackPatternId));
}

Expand All @@ -99,7 +100,7 @@ public Iterable<InjectorContract> injectorContracts(@PathVariable String attackP
public AttackPattern updateAttackPattern(
@NotBlank @PathVariable final String attackPatternId,
@Valid @RequestBody AttackPatternUpdateInput input) {
AttackPattern attackPattern = this.attackPatternRepository.findById(attackPatternId).orElseThrow();
AttackPattern attackPattern = this.attackPatternRepository.findById(attackPatternId).orElseThrow(ElementNotFoundException::new);
attackPattern.setUpdateAttributes(input);
attackPattern.setKillChainPhases(fromIterable(this.killChainPhaseRepository.findAllById(input.getKillChainPhasesIds())));
attackPattern.setUpdatedAt(Instant.now());
Expand All @@ -116,7 +117,7 @@ private List<AttackPattern> upsertAttackPatterns(List<AttackPatternCreateInput>
fromIterable(killChainPhaseRepository.findAllById(attackPatternInput.getKillChainPhasesIds()))
: List.of();
AttackPattern attackPatternParent = attackPatternInput.getParentId() != null ?
attackPatternRepository.findByStixId(attackPatternInput.getParentId()).orElseThrow() : null;
attackPatternRepository.findByStixId(attackPatternInput.getParentId()).orElseThrow(ElementNotFoundException::new) : null;
if (optionalAttackPattern.isEmpty()) {
AttackPattern newAttackPattern = new AttackPattern();
newAttackPattern.setStixId(attackPatternInput.getStixId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import io.openbas.rest.challenge.response.ChallengeInformation;
import io.openbas.rest.challenge.response.ChallengeResult;
import io.openbas.rest.challenge.response.ChallengesReader;
import io.openbas.rest.exception.ElementNotFoundException;
import io.openbas.rest.helper.RestBehavior;
import io.openbas.service.ChallengeService;
import io.openbas.service.ScenarioService;
Expand Down Expand Up @@ -101,7 +102,7 @@ public Iterable<Challenge> challenges() {
public Challenge updateChallenge(
@PathVariable String challengeId,
@Valid @RequestBody ChallengeUpdateInput input) {
Challenge challenge = challengeRepository.findById(challengeId).orElseThrow();
Challenge challenge = challengeRepository.findById(challengeId).orElseThrow(ElementNotFoundException::new);
challenge.setTags(fromIterable(tagRepository.findAllById(input.getTagIds())));
challenge.setDocuments(fromIterable(documentRepository.findAllById(input.getDocumentIds())));
challenge.setUpdateAttributes(input);
Expand Down Expand Up @@ -149,7 +150,7 @@ public Iterable<Challenge> exerciseChallenges(@PathVariable String exerciseId) {

@GetMapping("/api/player/challenges/{exerciseId}")
public ChallengesReader playerChallenges(@PathVariable String exerciseId, @RequestParam Optional<String> userId) {
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow();
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow(ElementNotFoundException::new);
final User user = impersonateUser(userRepository, userId);
if (user.getId().equals(ANONYMOUS)) {
throw new UnsupportedOperationException("User must be logged or dynamic player is required");
Expand All @@ -172,7 +173,7 @@ public ChallengesReader playerChallenges(@PathVariable String exerciseId, @Reque

@GetMapping("/api/observer/challenges/{exerciseId}")
public ChallengesReader observerChallenges(@PathVariable String exerciseId) {
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow();
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow(ElementNotFoundException::new);
ChallengesReader challengesReader = new ChallengesReader(exercise);
Iterable<Challenge> challenges = exerciseChallenges(exerciseId);
challengesReader.setExerciseChallenges(fromIterable(challenges).stream()
Expand Down Expand Up @@ -205,7 +206,7 @@ private boolean checkFlag(ChallengeFlag flag, String value) {

@PostMapping("/api/challenges/{challengeId}/try")
public ChallengeResult tryChallenge(@PathVariable String challengeId, @Valid @RequestBody ChallengeTryInput input) {
Challenge challenge = challengeRepository.findById(challengeId).orElseThrow();
Challenge challenge = challengeRepository.findById(challengeId).orElseThrow(ElementNotFoundException::new);
for (ChallengeFlag flag : challenge.getFlags()) {
if (checkFlag(flag, input.getValue())) {
return new ChallengeResult(true);
Expand Down
33 changes: 17 additions & 16 deletions openbas-api/src/main/java/io/openbas/rest/channel/ChannelApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import io.openbas.rest.channel.form.*;
import io.openbas.rest.channel.model.VirtualArticle;
import io.openbas.rest.channel.response.ChannelReader;
import io.openbas.rest.exception.ElementNotFoundException;
import io.openbas.rest.helper.RestBehavior;
import io.openbas.service.ScenarioService;
import jakarta.transaction.Transactional;
Expand Down Expand Up @@ -86,13 +87,13 @@ public Iterable<Channel> channels() {

@GetMapping("/api/channels/{channelId}")
public Channel channel(@PathVariable String channelId) {
return channelRepository.findById(channelId).orElseThrow();
return channelRepository.findById(channelId).orElseThrow(ElementNotFoundException::new);
}

@Secured(ROLE_ADMIN)
@PutMapping("/api/channels/{channelId}")
public Channel updateChannel(@PathVariable String channelId, @Valid @RequestBody ChannelUpdateInput input) {
Channel channel = channelRepository.findById(channelId).orElseThrow();
Channel channel = channelRepository.findById(channelId).orElseThrow(ElementNotFoundException::new);
channel.setUpdateAttributes(input);
channel.setUpdatedAt(Instant.now());
return channelRepository.save(channel);
Expand All @@ -101,7 +102,7 @@ public Channel updateChannel(@PathVariable String channelId, @Valid @RequestBody
@Secured(ROLE_ADMIN)
@PutMapping("/api/channels/{channelId}/logos")
public Channel updateChannelLogos(@PathVariable String channelId, @Valid @RequestBody ChannelUpdateLogoInput input) {
Channel channel = channelRepository.findById(channelId).orElseThrow();
Channel channel = channelRepository.findById(channelId).orElseThrow(ElementNotFoundException::new);
if (input.getLogoDark() != null) {
channel.setLogoDark(documentRepository.findById(input.getLogoDark()).orElse(null));
} else {
Expand Down Expand Up @@ -156,14 +157,14 @@ private List<Article> enrichArticleWithVirtualPublication(List<Inject> injects,
}

private Article enrichArticleWithVirtualPublication(List<Inject> injects, Article article) {
return enrichArticleWithVirtualPublication(injects, List.of(article)).stream().findFirst().orElseThrow();
return enrichArticleWithVirtualPublication(injects, List.of(article)).stream().findFirst().orElseThrow(ElementNotFoundException::new);
}

@GetMapping("/api/observer/channels/{exerciseId}/{channelId}")
@PreAuthorize("isExerciseObserver(#exerciseId)")
public ChannelReader observerArticles(@PathVariable String exerciseId, @PathVariable String channelId) {
ChannelReader channelReader;
Channel channel = channelRepository.findById(channelId).orElseThrow();
Channel channel = channelRepository.findById(channelId).orElseThrow(ElementNotFoundException::new);

Optional<Exercise> exerciseOpt = this.exerciseRepository.findById(exerciseId);
if (exerciseOpt.isPresent()) {
Expand All @@ -188,7 +189,7 @@ public ChannelReader playerArticles(
@PathVariable String channelId,
@RequestParam Optional<String> userId) {
ChannelReader channelReader;
Channel channel = channelRepository.findById(channelId).orElseThrow();
Channel channel = channelRepository.findById(channelId).orElseThrow(ElementNotFoundException::new);
List<Inject> injects;

Optional<Exercise> exerciseOpt = exerciseRepository.findById(exerciseId);
Expand Down Expand Up @@ -259,11 +260,11 @@ public ChannelReader playerArticles(
public Article createArticleForExercise(
@PathVariable String exerciseId,
@Valid @RequestBody ArticleCreateInput input) {
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow();
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow(ElementNotFoundException::new);
Article article = new Article();
article.setUpdateAttributes(input);
article.setChannel(channelRepository.findById(input.getChannelId()).orElseThrow());
article.setExercise(exerciseRepository.findById(exerciseId).orElseThrow());
article.setChannel(channelRepository.findById(input.getChannelId()).orElseThrow(ElementNotFoundException::new));
article.setExercise(exerciseRepository.findById(exerciseId).orElseThrow(ElementNotFoundException::new));
Article savedArticle = articleRepository.save(article);
List<String> articleDocuments = input.getDocuments();
List<Document> finalArticleDocuments = new ArrayList<>();
Expand All @@ -286,7 +287,7 @@ public Article createArticleForExercise(
@PreAuthorize("isExerciseObserver(#exerciseId)")
@GetMapping("/api/exercises/{exerciseId}/articles")
public Iterable<Article> exerciseArticles(@PathVariable String exerciseId) {
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow();
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow(ElementNotFoundException::new);
return enrichArticleWithVirtualPublication(exercise.getInjects(), exercise.getArticles());
}

Expand All @@ -296,11 +297,11 @@ public Article updateArticleForExercise(
@PathVariable String exerciseId,
@PathVariable String articleId,
@Valid @RequestBody ArticleUpdateInput input) {
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow();
Article article = articleRepository.findById(articleId).orElseThrow();
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow(ElementNotFoundException::new);
Article article = articleRepository.findById(articleId).orElseThrow(ElementNotFoundException::new);
List<String> newDocumentsIds = input.getDocuments();
List<String> currentDocumentIds = article.getDocuments().stream().map(Document::getId).toList();
article.setChannel(channelRepository.findById(input.getChannelId()).orElseThrow());
article.setChannel(channelRepository.findById(input.getChannelId()).orElseThrow(ElementNotFoundException::new));
article.setUpdateAttributes(input);
// Original List
List<Document> articleDocuments = new ArrayList<>(article.getDocuments());
Expand Down Expand Up @@ -344,7 +345,7 @@ public Article createArticleForScenario(
Scenario scenario = this.scenarioService.scenario(scenarioId);
Article article = new Article();
article.setUpdateAttributes(input);
article.setChannel(this.channelRepository.findById(input.getChannelId()).orElseThrow());
article.setChannel(this.channelRepository.findById(input.getChannelId()).orElseThrow(ElementNotFoundException::new));
article.setScenario(scenario);
Article savedArticle = this.articleRepository.save(article);
List<String> articleDocuments = input.getDocuments();
Expand Down Expand Up @@ -379,10 +380,10 @@ public Article updateArticleForScenario(
@PathVariable @NotBlank final String articleId,
@Valid @RequestBody ArticleUpdateInput input) {
Scenario scenario = this.scenarioService.scenario(scenarioId);
Article article = articleRepository.findById(articleId).orElseThrow();
Article article = articleRepository.findById(articleId).orElseThrow(ElementNotFoundException::new);
List<String> newDocumentsIds = input.getDocuments();
List<String> currentDocumentIds = article.getDocuments().stream().map(Document::getId).toList();
article.setChannel(channelRepository.findById(input.getChannelId()).orElseThrow());
article.setChannel(channelRepository.findById(input.getChannelId()).orElseThrow(ElementNotFoundException::new));
article.setUpdateAttributes(input);
// Original List
List<Document> articleDocuments = new ArrayList<>(article.getDocuments());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import io.openbas.config.OpenBASConfig;
import io.openbas.database.model.Collector;
import io.openbas.database.model.Injector;
import io.openbas.database.repository.CollectorRepository;
import io.openbas.rest.collector.form.CollectorCreateInput;
import io.openbas.rest.collector.form.CollectorUpdateInput;
import io.openbas.rest.exception.ElementNotFoundException;
import io.openbas.rest.helper.RestBehavior;
import io.openbas.service.FileService;
import jakarta.annotation.Resource;
Expand Down Expand Up @@ -63,7 +63,7 @@ private Collector updateCollector(Collector collector, String type, String name,
@Secured(ROLE_ADMIN)
@PutMapping("/api/collectors/{collectorId}")
public Collector updateCollector(@PathVariable String collectorId, @Valid @RequestBody CollectorUpdateInput input) {
Collector collector = collectorRepository.findById(collectorId).orElseThrow();
Collector collector = collectorRepository.findById(collectorId).orElseThrow(ElementNotFoundException::new);
return updateCollector(collector, collector.getType(), collector.getName(), collector.getPeriod(), input.getLastExecution());
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
package io.openbas.rest.comcheck;

import io.openbas.database.model.*;
import io.openbas.database.repository.TeamRepository;
import io.openbas.database.repository.ComcheckRepository;
import io.openbas.database.repository.ComcheckStatusRepository;
import io.openbas.database.repository.ExerciseRepository;
import io.openbas.database.repository.TeamRepository;
import io.openbas.rest.comcheck.form.ComcheckInput;
import io.openbas.rest.exception.ElementNotFoundException;
import io.openbas.rest.helper.RestBehavior;
import jakarta.transaction.Transactional;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.transaction.Transactional;
import jakarta.validation.Valid;
import java.util.List;

import static io.openbas.helper.StreamHelper.fromIterable;
Expand Down Expand Up @@ -49,7 +50,7 @@ public void setExerciseRepository(ExerciseRepository exerciseRepository) {
@Transactional(rollbackOn = Exception.class)
@GetMapping("/api/comcheck/{comcheckStatusId}")
public ComcheckStatus checkValidation(@PathVariable String comcheckStatusId) {
ComcheckStatus comcheckStatus = comcheckStatusRepository.findById(comcheckStatusId).orElseThrow();
ComcheckStatus comcheckStatus = comcheckStatusRepository.findById(comcheckStatusId).orElseThrow(ElementNotFoundException::new);
Comcheck comcheck = comcheckStatus.getComcheck();
if (!comcheck.getState().equals(Comcheck.COMCHECK_STATUS.RUNNING)) {
throw new UnsupportedOperationException("This comcheck is closed.");
Expand Down Expand Up @@ -80,7 +81,7 @@ public Comcheck communicationCheck(@PathVariable String exerciseId,
check.setUpdateAttributes(comCheck);
check.setName(comCheck.getName());
check.setStart(now());
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow();
Exercise exercise = exerciseRepository.findById(exerciseId).orElseThrow(ElementNotFoundException::new);
check.setExercise(exercise);
// 02. Get users
List<String> teamIds = comCheck.getTeamIds();
Expand Down
Loading

0 comments on commit dfb6fa0

Please sign in to comment.