From 2a2d70c2b50a70fcdd71337c9f08f652f67a99a1 Mon Sep 17 00:00:00 2001 From: Davi Aliaga Date: Mon, 19 Oct 2026 10:39:42 -0300 Subject: [PATCH 1/4] =?UTF-8?q?feat/exception:=20adiciona=20exce=C3=A7?= =?UTF-8?q?=C3=B5es=20personalizadas=20e=20ajustes=20no=20workflow=20de=20?= =?UTF-8?q?seguran=C3=A7a?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/validacao.yml | 6 +++++- .../handler/exception/BusinessRuleException.java | 7 +++++++ .../exception/FirebaseAccessRevokedException.java | 9 +++++++++ .../handler/exception/FirebaseIdTokenException.java | 9 +++++++++ .../acta/common/handler/exception/RegexException.java | 7 +++++++ .../handler/exception/UniqueViolationException.java | 11 +++++++++++ 6 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/main/java/br/com/acta/common/handler/exception/BusinessRuleException.java create mode 100644 src/main/java/br/com/acta/common/handler/exception/FirebaseAccessRevokedException.java create mode 100644 src/main/java/br/com/acta/common/handler/exception/FirebaseIdTokenException.java create mode 100644 src/main/java/br/com/acta/common/handler/exception/RegexException.java create mode 100644 src/main/java/br/com/acta/common/handler/exception/UniqueViolationException.java diff --git a/.github/workflows/validacao.yml b/.github/workflows/validacao.yml index 66b4269..f2d2a45 100644 --- a/.github/workflows/validacao.yml +++ b/.github/workflows/validacao.yml @@ -55,6 +55,10 @@ jobs: # procura vulnerabilidades no código java seguranca: runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write steps: - uses: actions/checkout@v4 @@ -77,4 +81,4 @@ jobs: clean package -DskipTests # publica os alertas na aba security do github - - uses: github/codeql-action/analyze@v4 \ No newline at end of file + - uses: github/codeql-action/analyze@v4 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 From 1a6c83f61b7b69b4574ae7dacb982c64756fa89f Mon Sep 17 00:00:00 2001 From: Davi Aliaga Date: Mon, 19 Oct 2026 10:40:46 -0300 Subject: [PATCH 2/4] feat/handler: adiciona GlobalExceptionHandler para tratamento centralizado de erros --- .../handler/GlobalExceptionHandler.java | 183 ++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 src/main/java/br/com/acta/common/handler/GlobalExceptionHandler.java 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 From 14e2c2b78e9d5f3322ae6a660b2c5c1b8dde8939 Mon Sep 17 00:00:00 2001 From: Davi Aliaga Date: Mon, 19 Oct 2026 10:44:57 -0300 Subject: [PATCH 3/4] =?UTF-8?q?feat/handler:=20adiciona=20classe=20ErroRes?= =?UTF-8?q?ponse=20para=20padroniza=C3=A7=C3=A3o=20de=20respostas=20de=20e?= =?UTF-8?q?rro?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../br/com/acta/common/handler/ErroResponse.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/main/java/br/com/acta/common/handler/ErroResponse.java 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 From 19bd5eb1d89ceb7823e58d7e57aeb6e7dc74e72a Mon Sep 17 00:00:00 2001 From: Davi Aliaga Date: Mon, 19 Oct 2026 10:53:27 -0300 Subject: [PATCH 4/4] =?UTF-8?q?feat/handler:=20adiciona=20classe=20ErroRes?= =?UTF-8?q?ponse=20para=20padroniza=C3=A7=C3=A3o=20de=20respostas=20de=20e?= =?UTF-8?q?rro?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/validacao.yml | 31 ------------------------------- 1 file changed, 31 deletions(-) diff --git a/.github/workflows/validacao.yml b/.github/workflows/validacao.yml index f2d2a45..3ac95f7 100644 --- a/.github/workflows/validacao.yml +++ b/.github/workflows/validacao.yml @@ -51,34 +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 - permissions: - actions: read - contents: read - security-events: write - - 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