Sub topic 12
Keeping internal details out of responses
This chapter assumes you have read the earlier chapters on @RestControllerAdvice, ProblemDetail and the default /error behavior. You should be comfortable with Spring Boot 3, ApiExceptionHandler as built earlier, and basic logging with SLF4J.
Why error responses leak
An error response is the one place where your application talks to a client that may be hostile. Exception messages, stack traces and validation details are written for developers. If they reach a client, they can reveal several kinds of information:
- Class and package names, which tell an attacker which framework versions and libraries you use.
- SQL fragments, table names and constraint names from database exceptions.
- Host names, file paths and connection URLs from I/O and configuration exceptions.
- Whether a record exists, from the difference between "not found" and "forbidden".
Most leaks are not in the defaults. They come from code someone wrote to be helpful, such as return ex.getMessage() in a catch-all handler.
The rule used in the rest of this chapter: a 4xx message is written for the client, and a 5xx message never is. A 4xx body can name the field or resource the client got wrong. A 5xx body says only that something failed and gives an identifier to quote to support.
Locking down the default `/error` response
Requests that never reach your handlers still produce a response. Examples are a 404 for an unmapped URL, or an exception thrown from a servlet filter. Spring Boot's BasicErrorController writes those responses, and the server.error.* properties control how much it includes.
# Return RFC 9457 problem details for exceptions raised by Spring MVC itself
spring.mvc.problemdetails.enabled=true
# Keep internal details out of the default /error response
server.error.include-message=never
server.error.include-binding-errors=never
server.error.include-stacktrace=never
server.error.include-exception=falseThese values are the defaults in current Spring Boot versions. Setting them explicitly still has a purpose. It documents the intent, and it protects you if someone turns on include-stacktrace=always in a development profile and the setting is later copied into production.
| Property | Safe value | What it controls |
|---|---|---|
| `server.error.include-message` | `never` | The exception message in the `message` field |
| `server.error.include-binding-errors` | `never` | The `errors` array from binding and validation |
| `server.error.include-stacktrace` | `never` | The `trace` field |
| `server.error.include-exception` | `false` | The exception class name in the `exception` field |
The values always and on_param are also accepted. on_param lets a caller add ?trace=true to the URL, so it is the wrong choice for anything reachable from the internet.
Leaks that come from your own handlers
The common mistake is a catch-all handler that forwards the message:
@ExceptionHandler(Exception.class)
public ProblemDetail handleUnexpected(Exception ex) {
// Wrong: the message may contain SQL, hosts, paths or credentials
return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
}A DataIntegrityViolationException message can include the statement and the constraint name. A connection failure can include the JDBC URL. Neither belongs in a response.
Domain exceptions need the opposite check. OrderNotFoundException is safe to forward because you wrote its message, and it contains only the id the client sent. That is the test to apply to each handler. Ask whether the text came from code you control and whether it is meant to be read by a client. If either answer is no, send a fixed string.
The flow below shows where each kind of information goes.
A catch-all handler with an error id
If the client gets no detail, support still needs a way to find the matching log entry. The usual answer is a random error id. The server writes it to the log next to the stack trace and also sends it in the response. A user who reports "error 3f2a..." gives you something you can search for.
Replace the handleUnexpected method in ApiExceptionHandler with this version. Also add import java.util.UUID;.
@ExceptionHandler(Exception.class)
public ProblemDetail handleUnexpected(Exception ex) {
String errorId = UUID.randomUUID().toString();
log.error("Unhandled exception, errorId={}", errorId, ex);
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
problem.setTitle("Internal server error");
problem.setProperty("errorId", errorId);
return problem;
}The exception goes to log.error as the last argument, so the logger prints the whole stack trace. Nothing from it is copied into the response. If your application has a trace id from Micrometer Tracing or a similar library, you can use that value instead of a random UUID.
Validation and input errors
Validation messages are generally safe, because they come from your annotations, such as "must not be blank". Two details still need checking:
- Rejected values.
FieldErrorexposesgetRejectedValue(). Do not echo it for fields such as passwords, tokens or card numbers. The handler from the validation chapter uses only the field name and the default message, which avoids the problem. Keep it that way. - Custom messages. If a custom constraint builds its message from internal data, such as a database lookup, that data goes to the client.
For malformed JSON or a bad path variable, the built-in handlers in ResponseEntityExceptionHandler produce short, generic details. Do not override them with ex.getMessage(). The message on a HttpMessageNotReadableException can carry Jackson internals such as class and field paths.
Not found versus forbidden
Information can leak through status codes too. Suppose /orders/42 returns 403 when order 42 belongs to someone else and 404 when it does not exist. A caller can then learn which order ids exist. For resources that are private to a user, return 404 in both cases. Look the order up with the current user's id included in the query, and treat "not found for this user" as the single missing case.
Verifying the behavior with a test
Treat the no-leak rule as behavior to test. This test throws an exception whose message contains an internal URL, then checks that the URL never appears in the response.
package com.example.orders;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@WebMvcTest(UnexpectedErrorTest.BoomController.class)
class UnexpectedErrorTest {
@RestController
static class BoomController {
@GetMapping("/boom")
String boom() {
throw new IllegalStateException("Cannot connect to jdbc:postgresql://db.internal:5432/orders");
}
}
@Autowired
MockMvc mockMvc;
@Test
void unexpectedErrorHidesInternalMessage() throws Exception {
mockMvc.perform(get("/boom"))
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.detail").value("An unexpected error occurred"))
.andExpect(jsonPath("$.errorId").isNotEmpty())
.andExpect(content().string(not(containsString("jdbc"))));
}
}The @WebMvcTest slice picks up ApiExceptionHandler automatically, so the test exercises the real handler.
Common mistakes
- Returning
ex.getMessage()orex.toString()from a catch-all handler. - Relying on
server.error.*to protect bodies that your own handlers build. - Logging the stack trace and also returning it, so the same details exist in two places.
- Using
include-stacktrace=on_paramoralwaysin a shared environment because it was convenient during development. - Forgetting that a servlet filter exception bypasses
@RestControllerAdviceand goes through/error, where only the properties apply.
Exercise
Your @RestControllerAdvice has a handler for DataIntegrityViolationException that returns ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage()). You have set server.error.include-message=never. Why is the message still sent to clients, and how would you fix the handler?
Show answer
The server.error.* properties only affect responses written by BasicErrorController. This handler builds its own body, so the property is not consulted and the message, which may contain SQL and constraint names, goes out. Replace ex.getMessage() with a fixed client-safe string such as "The request conflicts with existing data", and log the exception on the server with log.warn or log.error.
Exercise
A user reports a failed request and quotes the error id 3f2a9c1e. What must the server have done for this id to help you, and why is it better than putting the stack trace in the response?
Show answer
The handler must have generated the id, written it to the log together with the full exception, and returned the same id in the response body. You can then search the logs for the id and find the stack trace. Returning the trace instead would expose class names, library versions and paths to every client, including attackers.