diff --git a/.github/workflows/validacao.yml b/.github/workflows/validacao.yml index 66b4269..3ac95f7 100644 --- a/.github/workflows/validacao.yml +++ b/.github/workflows/validacao.yml @@ -51,30 +51,3 @@ jobs: bash ./mvnw -B -Daether.transport.http.retryHandler.count=5 -Daether.transport.http.retryHandler.serviceUnavailable=429,502,503 clean verify - - # procura vulnerabilidades no código java - seguranca: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - # prepara o codeql para analisar java - - uses: github/codeql-action/init@v4 - with: - languages: java - build-mode: manual - - - uses: actions/setup-java@v5 - with: - distribution: temurin - java-version: '17' - - # compila para disponibilizar as classes ao codeql - - run: >- - bash ./mvnw -B -Daether.transport.http.retryHandler.count=5 - -Daether.transport.http.retryHandler.serviceUnavailable=429,502,503 - clean package -DskipTests - - # publica os alertas na aba security do github - - uses: github/codeql-action/analyze@v4 \ No newline at end of file diff --git a/src/main/java/br/com/acta/common/handler/ErroResponse.java b/src/main/java/br/com/acta/common/handler/ErroResponse.java new file mode 100644 index 0000000..e3d9a36 --- /dev/null +++ b/src/main/java/br/com/acta/common/handler/ErroResponse.java @@ -0,0 +1,14 @@ +package br.com.acta.common.handler; + +import java.time.LocalDateTime; +import java.util.List; + +public record ErroResponse( + List mensagens, + Integer httpStatus, + LocalDateTime timestamp +) { + public ErroResponse(List mensagens, Integer httpStatus){ + this(mensagens, httpStatus, LocalDateTime.now()); + } +} \ No newline at end of file diff --git a/src/main/java/br/com/acta/common/handler/GlobalExceptionHandler.java b/src/main/java/br/com/acta/common/handler/GlobalExceptionHandler.java new file mode 100644 index 0000000..e9a7171 --- /dev/null +++ b/src/main/java/br/com/acta/common/handler/GlobalExceptionHandler.java @@ -0,0 +1,183 @@ +package br.com.acta.common.handler; + +import java.util.List; + +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.OptimisticLockingFailureException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; +import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.method.annotation.HandlerMethodValidationException; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import org.springframework.web.servlet.resource.NoResourceFoundException; +import br.com.acta.common.handler.exception.BusinessRuleException; +import br.com.acta.common.handler.exception.FirebaseAccessRevokedException; +import br.com.acta.common.handler.exception.FirebaseIdTokenException; +import jakarta.validation.ConstraintViolationException; +import lombok.extern.slf4j.Slf4j; + +@ControllerAdvice +@Slf4j +public class GlobalExceptionHandler { + @ExceptionHandler(FirebaseIdTokenException.class) + public ResponseEntity handleFirebaseIdToken(FirebaseIdTokenException fite){ + log.error("mensagem", fite); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body(new ErroResponse(List.of(fite.getMessage()), 401)); + } + + @ExceptionHandler(FirebaseAccessRevokedException.class) + public ResponseEntity handleFirebaseAccessRevoked(FirebaseAccessRevokedException fare){ + log.error("mensagem", fare); + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body(new ErroResponse(List.of(fare.getMessage()), 403)); + } + + @ExceptionHandler(AuthenticationCredentialsNotFoundException.class) + public ResponseEntity handleAuthenticationCredentialsNotFound(AuthenticationCredentialsNotFoundException acnfe){ + log.error("mensagem", acnfe); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body(new ErroResponse(List.of(acnfe.getMessage()), 401)); + } + + @ExceptionHandler(BusinessRuleException.class) + public ResponseEntity handleBusinessRule(BusinessRuleException bre){ + log.error("mensagem", bre); + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_CONTENT) + .body(new ErroResponse(List.of(bre.getMessage()), 422)); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleValidation(MethodArgumentNotValidException manve){ + log.error("mensagem", manve); + List mensagens = manve.getBindingResult() + .getFieldErrors() + .stream() + .map(e -> e.getField() + ": " + e.getDefaultMessage()) + .toList(); + + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ErroResponse(mensagens, 400)); + } + + @ExceptionHandler(HandlerMethodValidationException.class) + public ResponseEntity handleValidation(HandlerMethodValidationException hmve) { + log.error("mensagem", hmve); + List mensagens = hmve.getParameterValidationResults() + .stream() + .flatMap(r -> r.getResolvableErrors().stream()) + .map(e -> e.getDefaultMessage() != null + ? e.getDefaultMessage() + : "Um parâmetro informado é inválido") + .toList(); + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ErroResponse(mensagens, 400)); + } + + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity handleIllegalState(IllegalStateException ise){ + log.error("mensagem", ise); + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ErroResponse(List.of(ise.getMessage()), 400)); + } + + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity handleConstraint(ConstraintViolationException cve){ + log.error("mensagem", cve); + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ErroResponse(List.of("Algum dos parâmetros informados é inválido"), 400)); + } + + @ExceptionHandler(HttpMediaTypeNotAcceptableException.class) + public ResponseEntity handleHttpMediaNotAcceptable(HttpMediaTypeNotAcceptableException hmtnae) { + log.error("mensagem", hmtnae); + return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE) + .body(new ErroResponse(List.of("O tipo de resposta solicitado não é suportado"), 406)); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity handleValidation(HttpMessageNotReadableException hmnre){ + log.error("mensagem", hmnre); + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ErroResponse(List.of("O corpo da requisição está inválido ou mal formado"), 400)); + } + + @ExceptionHandler(MissingServletRequestParameterException.class) + public ResponseEntity handleMissingParam(MissingServletRequestParameterException msrpe){ + log.error("mensagem", msrpe); + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ErroResponse(List.of("Um parâmetro obrigatório não foi informado"), 400)); + } + + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ResponseEntity handleMethodMismatch(MethodArgumentTypeMismatchException matme){ + log.error("mensagem", matme); + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ErroResponse(List.of("Um parâmetro foi informado com o tipo inválido"), 400)); + } + + @ExceptionHandler(NoResourceFoundException.class) + public ResponseEntity handleNoResourceFound(NoResourceFoundException nrfe){ + log.error("mensagem", nrfe); + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(new ErroResponse(List.of("O recurso solicitado não foi encontrado"), 404)); + } + + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public ResponseEntity handleHttpRequest(HttpRequestMethodNotSupportedException hrmnse){ + log.error("mensagem", hrmnse); + return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) + .body(new ErroResponse(List.of("O método HTTP utilizado não é permitido para esta rota"), 405)); + } + + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + public ResponseEntity handleHttpMedia(HttpMediaTypeNotSupportedException hmtnse){ + log.error("mensagem", hmtnse); + return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE) + .body(new ErroResponse(List.of("O tipo de conteúdo enviado não é suportado"), 415)); + } + + @ExceptionHandler(AccessDeniedException.class) + public ResponseEntity handleAccessDenied(AccessDeniedException ade){ + log.error("mensagem", ade); + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body(new ErroResponse(List.of("Você não tem permissão de acesso para este recurso"), 403)); + } + + @ExceptionHandler(DataIntegrityViolationException.class) + public ResponseEntity handleDataIntegrity(DataIntegrityViolationException dive){ + log.error("mensagem", dive); + return ResponseEntity.status(HttpStatus.CONFLICT) + .body(new ErroResponse(List.of("Não foi possível realizar a operação por conflito com os dados existentes"), 409)); + } + + @ExceptionHandler(OptimisticLockingFailureException.class) + public ResponseEntity handleOptimisticLocking(OptimisticLockingFailureException olfe){ + log.error("mensagem", olfe); + return ResponseEntity.status(HttpStatus.CONFLICT) + .body(new ErroResponse(List.of("Este registro foi alterado por outra operação, tente novamente"), 409)); + } + + @ExceptionHandler(RuntimeException.class) + public ResponseEntity handleRuntime(RuntimeException re){ + log.error("mensagem", re); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ErroResponse(List.of("Ocorreu um erro interno inesperado"), 500)); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleException(Exception e){ + log.error("mensagem", e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ErroResponse(List.of("Ocorreu um erro interno inesperado"), 500)); + } +} \ No newline at end of file diff --git a/src/main/java/br/com/acta/common/handler/exception/BusinessRuleException.java b/src/main/java/br/com/acta/common/handler/exception/BusinessRuleException.java new file mode 100644 index 0000000..12b5c4c --- /dev/null +++ b/src/main/java/br/com/acta/common/handler/exception/BusinessRuleException.java @@ -0,0 +1,7 @@ +package br.com.acta.common.handler.exception; + +public class BusinessRuleException extends RuntimeException { + public BusinessRuleException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/br/com/acta/common/handler/exception/FirebaseAccessRevokedException.java b/src/main/java/br/com/acta/common/handler/exception/FirebaseAccessRevokedException.java new file mode 100644 index 0000000..3e1fa50 --- /dev/null +++ b/src/main/java/br/com/acta/common/handler/exception/FirebaseAccessRevokedException.java @@ -0,0 +1,9 @@ +package br.com.acta.common.handler.exception; + +import org.springframework.security.access.AccessDeniedException; + +public class FirebaseAccessRevokedException extends AccessDeniedException { + public FirebaseAccessRevokedException() { + super("O ID Token enviado não é válido com nenhum usuário do ACTA"); + } +} \ No newline at end of file diff --git a/src/main/java/br/com/acta/common/handler/exception/FirebaseIdTokenException.java b/src/main/java/br/com/acta/common/handler/exception/FirebaseIdTokenException.java new file mode 100644 index 0000000..be91563 --- /dev/null +++ b/src/main/java/br/com/acta/common/handler/exception/FirebaseIdTokenException.java @@ -0,0 +1,9 @@ +package br.com.acta.common.handler.exception; + +import org.springframework.security.authentication.BadCredentialsException; + +public class FirebaseIdTokenException extends BadCredentialsException { + public FirebaseIdTokenException() { + super("O ID Token do Firebase enviado não é válido"); + } +} \ No newline at end of file diff --git a/src/main/java/br/com/acta/common/handler/exception/RegexException.java b/src/main/java/br/com/acta/common/handler/exception/RegexException.java new file mode 100644 index 0000000..3d67770 --- /dev/null +++ b/src/main/java/br/com/acta/common/handler/exception/RegexException.java @@ -0,0 +1,7 @@ +package br.com.acta.common.handler.exception; + +public class RegexException extends RuntimeException { + public RegexException(String message) { + super("O " + message + " digitado é inválido"); + } +} \ No newline at end of file diff --git a/src/main/java/br/com/acta/common/handler/exception/UniqueViolationException.java b/src/main/java/br/com/acta/common/handler/exception/UniqueViolationException.java new file mode 100644 index 0000000..558d2be --- /dev/null +++ b/src/main/java/br/com/acta/common/handler/exception/UniqueViolationException.java @@ -0,0 +1,11 @@ +package br.com.acta.common.handler.exception; + +public class UniqueViolationException extends RuntimeException { + public UniqueViolationException(String recurso) { + super("Já existe um registro para " + recurso); + } + + public UniqueViolationException(String primeiroRecurso, String segundoRecurso){ + super("Já existe um vínculo entre " + primeiroRecurso + " e " + segundoRecurso); + } +} \ No newline at end of file