Skip to lesson

Leaking data through entities and error messages

The profile screen shows a name and an e-mail, but the JSON behind it also carries a password hash, and a failed request returns raw SQL. Who decides what leaves the server?

Returning an entity sends every field

Excessive data exposure is an API sending more data than the caller should see, usually by returning a database entity whose every getter becomes a JSON field. The API trusts the client to ignore the rest.

GET /api/v1/me returns the User entity itself. Read what the client receives.

Example 1 · Mistake: GET /api/v1/me returns the User entity

Runs in: the shoplite-api Spring Boot project (a copy with the mistake added)

Java
package com.shoplite.user;
import org.springframework.security.core.annotation.AuthenticationPrincipal;import org.springframework.security.oauth2.jwt.Jwt;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;
import com.shoplite.common.ResourceNotFoundException;
// MISTAKE: the controller returns the User entity itself.// (User.customer also got @JsonIgnore, to stop a 500 "Failed to write request" on the lazy field.)@RestControllerclass MeController {
    private final UserRepository users;
    MeController(UserRepository users) {        this.users = users;    }
    @GetMapping("/api/v1/me")    User me(@AuthenticationPrincipal Jwt jwt) {        Integer userId = Integer.valueOf(jwt.getSubject());      // sub = the user id        return users.findById(userId)                .orElseThrow(() -> new ResourceNotFoundException("User", userId));    }}
Sample output
$ curl -s http://localhost:8080/api/v1/me -H "Authorization: Bearer $TOKEN"
{"email":"asha.rao@example.com","passwordHash":"{bcrypt}$2a$10$tf367IbGb5L.PfxIpb8Uq.hnqlV4KsvaVloXYH/WlwE5GbZ55aWvG","id":2,"enabled":true,"createdAt":"2026-10-16T13:53:29","roles":["CUSTOMER"]}

What this code does

  • Every getter of User became a JSON field, including passwordHash. With the hash, an attacker can try millions of guesses offline, with no login limit to stop them.
  • enabled and createdAt were never meant for clients either, and the order of the fields is not even the contract's order.
  • Hiding one field with @JsonIgnore is the wrong fix: the next column added to app_user leaks automatically. Example 2 replaces the entity with a DTO.

A JPA entity such as User mirrors a table row, and Jackson writes every property that has a getter: the password hash, the enabled flag and anything added to the table next year. Anyone can read a response in the browser's network tab or with curl, so a field that is sent is a field that is public to that caller.

Entities also fail in confusing ways. With ShopLite's lazy customer field and open-in-view off, GET /api/v1/me first answered 500 "Failed to write request". The developer silenced it with @JsonIgnore on customer, and the endpoint "worked", leaking the hash instead.

Predict the output

What does the client receive?

Read the controller, then pick the JSON fields the client gets.

Round 1 of 2

GET /me returns the entity itself. Which fields reach the client?

@Entity
class User {
Integer id;
String email;
String passwordHash;
boolean enabled;
// a getter for every field
}
@GetMapping("/me")
User me() {
return currentUser;
}
OWASP Top 10 2025 counts this under A01 Broken Access Control (exposing data to users who should not see it). In ShopLite's threat model it is risk R8.

Response DTOs and mass assignment

A response DTO is a small record that lists exactly the fields one endpoint returns. It works as an allow-list: a new column in the table stays private until someone adds it to the record on purpose.

The safe UserResponse record, then a sign-up request where the client chooses its own role.

Example 2 · Fix: the endpoint returns a UserResponse record

Runs in: the shoplite-api Spring Boot project

UserResponse.javaJava
package com.shoplite.user;
import java.util.List;
import com.shoplite.customer.Customer;
/** * What the API says about an account: an allow-list of safe fields. * There is deliberately no password hash, no enabled flag and no failed-login data here. */public record UserResponse(Integer id, String email, String fullName, Integer customerId, List<String> roles) {
    static UserResponse from(User user) {        List<String> roles = user.getRoles().stream().sorted().map(Role::name).toList();        Customer customer = user.getCustomer();                  // null for staff accounts        return new UserResponse(user.getId(), user.getEmail(),                customer == null ? null : customer.getFullName(),                customer == null ? null : customer.getId(), roles);    }}
// MeController: UserResponse me(@AuthenticationPrincipal Jwt jwt) { return userService.me(Integer.valueOf(jwt.getSubject())); }// UserService.me runs in a read-only transaction, so the lazy customer loads safely.
Sample output
$ curl -s http://localhost:8080/api/v1/me -H "Authorization: Bearer $TOKEN"
{"id":2,"email":"asha.rao@example.com","fullName":"Asha Rao","customerId":1,"roles":["CUSTOMER"]}

What this code does

  • The record names five fields, and only those five can ever leave the server. A new column needs a deliberate change here to become visible.
  • The mapping happens in the service, inside the transaction, so lazy loading works and the controller never touches an entity.
  • The response also matches the API contract's field order, because a record keeps its components in the order written.

Example 3 · Mass assignment: the client picks its own role

Runs in: the shoplite-api Spring Boot project

SignUpRequest.javaJava
// MISTAKE (in SignUpRequest): the request record has a field the client must not controlpublic record SignUpRequest(String fullName, String email, String password, String phone,                            Role role) {}
// MISTAKE (in UserService.register): the value is used as it arrivesUser user = users.saveAndFlush(new User(email, passwordEncoder.encode(request.password()), customer,        request.role() == null ? Role.CUSTOMER : request.role()));
// FIX: SignUpRequest has no role; UserService fixes it: new User(email, hash, customer, Role.CUSTOMER)
Sample output
$ curl -s -X POST http://localhost:8080/api/v1/auth/register -H "Content-Type: application/json" \
    -d '{"fullName":"Karan Joshi","email":"karan.joshi@example.com","password":"karan-long-password-1","phone":null,"role":"ADMIN"}'

With the mistake:
{"id":4,"email":"karan.joshi@example.com","fullName":"Karan Joshi","customerId":9,"roles":["ADMIN"]}

After the fix:
HTTP/1.1 400
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/malformed-request","title":"Malformed request","status":400,"detail":"Unknown field role.","instance":"/api/v1/auth/register"}

What this code does

  • One extra JSON field made a stranger an admin. Nothing looked wrong in the code review, because role seemed like a harmless optional field.
  • The fix removes the field from the request record, so the value has nowhere to go, and fixes the role in the service.
  • The 400 comes from fail-on-unknown-properties=true. Without it Jackson would silently drop role: safe, but the client would never learn that its request was wrong.

Mass assignment happens when a request body is bound straight onto an object with more fields than the client may set, such as a role or customerId. A customer then sends "role": "ADMIN" at sign-up and becomes an admin.

ShopLite's request records contain only what the client may choose, the role is fixed in UserService, and spring.jackson.deserialization.fail-on-unknown-properties=true turns any extra field into a 400 instead of silently ignoring it.

Stack traces, SQL and class names in error responses

A catch-all handler that copies ex.getMessage() into the response, then the safe version.

Properties
# Boot's defaults, shown for clarity: keep them like this in every shared environmentspring.web.error.include-stacktrace=neverspring.web.error.include-message=neverspring.web.error.include-exception=false

Example 4 · Mistake and fix: the catch-all error handler

Runs in: the shoplite-api Spring Boot project

Java
// MISTAKE: the raw exception message goes to the client@ExceptionHandler(Exception.class)public ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) {    return ProblemKind.INTERNAL_ERROR.problem(ex.getMessage());}
// FIX (ShopLite's GlobalExceptionHandler): the cause goes to the log, the client gets one safe sentence@ExceptionHandler(Exception.class)public ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) {    log.error("Unexpected error on {} {}", request.getMethod(), request.getRequestURI(), ex);    return ProblemKind.INTERNAL_ERROR.problem("Something went wrong on our side. Please try again later.");}
Sample output
(a migration renamed products.stock while the old version of the app was still running)

With the mistake:
$ curl -s http://localhost:8080/api/v1/products/1
{"type":"https://shoplite.example/problems/internal-error","title":"Internal server error","status":500,"detail":"JDBC exception executing SQL [select p1_0.product_id,p1_0.category_id,p1_0.is_active,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?] [Unknown column 'p1_0.stock' in 'field list'] [n/a]; SQL [n/a]","instance":"/api/v1/products/1"}

After the fix:
$ curl -s http://localhost:8080/api/v1/products/1
{"type":"https://shoplite.example/problems/internal-error","title":"Internal server error","status":500,"detail":"Something went wrong on our side. Please try again later.","instance":"/api/v1/products/1"}

Server log after the fix:
ERROR ... c.s.common.GlobalExceptionHandler : Unexpected error on GET /api/v1/products/1
org.springframework.dao.InvalidDataAccessResourceUsageException: JDBC exception executing SQL [...]

What this code does

  • With the mistake, one failed query reveals the table name, every column, the alias style of Hibernate and that the database is MySQL.
  • After the fix the client gets the contract's generic 500, and the full exception with its stack trace is in the server log, where developers can read it.
  • The handler stays a catch-all on purpose: every exception that no specific handler knows becomes this safe answer.

An error response is for the client: a status, a kind and one safe sentence. A stack trace, an SQL statement, a table or constraint name or a Java class name tells an attacker how the app is built, which database it uses and which input broke it. Database exceptions put the full SQL in their message, so the first unexpected failure publishes your schema.

Spring Boot's own error page is safe by default: spring.web.error.include-stacktrace and include-message default to never (in Boot 4 these replaced the old server.error.* names). Never set them to always outside your laptop. ShopLite goes further: one GlobalExceptionHandler answers every unexpected exception with a generic 500 ProblemDetail and logs the real cause on the server.

Different messages for 'no such user' and 'wrong password'

Account enumeration is finding out which e-mail addresses have an account, because login answers "no such user" and "wrong password" differently. A script can sort any list of addresses into the two groups.

Two login failures that give different texts, and the fix that gives one.

Example 5 · Account enumeration through login messages

Runs in: the shoplite-api Spring Boot project

Java
// MISTAKE (two lines that look harmless, in SecurityConfig and GlobalExceptionHandler):provider.setHideUserNotFoundExceptions(false);return ProblemKind.UNAUTHORIZED.problem(ex.getMessage());
// FIX (ShopLite): keep Spring's default and send one fixed sentence@ExceptionHandler(AuthenticationException.class)public ProblemDetail handleFailedLogin(AuthenticationException ex) {    return ProblemKind.UNAUTHORIZED.problem("Email or password is wrong.");}
Sample output
With the mistake:
$ curl -s -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" -d '{"email":"nobody@example.com","password":"x"}'
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"No account for the given e-mail","instance":"/api/v1/auth/login"}
$ curl -s -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" -d '{"email":"asha.rao@example.com","password":"x"}'
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Bad credentials","instance":"/api/v1/auth/login"}

After the fix (both requests):
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Email or password is wrong.","instance":"/api/v1/auth/login"}

What this code does

  • The status is 401 both times, but the detail differs, and that is enough: a script can now sort any list of e-mails into "has an account" and "does not".
  • "No account for the given e-mail" is the message ShopLite's own DatabaseUserDetailsService puts in UsernameNotFoundException. It was written for the log, not for clients.
  • After the fix, the message is a constant: no exception text can reach the client by accident.

A script that knows who uses ShopLite can aim password guessing or phishing at exactly those people. The fix is one message for every login failure: "Email or password is wrong." Spring's DaoAuthenticationProvider helps: by default it turns UsernameNotFoundException into BadCredentialsException (hideUserNotFoundExceptions is true), and it still runs a BCrypt check on a dummy hash for unknown users, so both answers take about the same time.

Sign-up is harder: ShopLite's contract answers 409 for a taken e-mail, which reveals that the account exists. That is an accepted trade-off for a shop, kept in check by rate limits; high-risk apps send "check your e-mail" for both cases instead.

Reviewing a response body field by field

A response review reads one real response of every endpoint and asks for each field: does the caller need it, and is it allowed to see it? Use a real request, because nested objects and error paths add fields you did not expect.

A small review program that checks each field of a real response against a deny-list and against the contract.

Example 6 · A field-by-field response review in code

ResponseReviewDemo.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Set;
public class ResponseReviewDemo {    static final List<String> SENSITIVE = List.of("password", "hash", "token", "secret", "enabled", "failed");
    static void review(String endpoint, Map<String, Object> body, Set<String> allowed) {        System.out.println(endpoint);        for (String field : body.keySet()) {            String lower = field.toLowerCase(Locale.ROOT);            boolean sensitive = SENSITIVE.stream().anyMatch(lower::contains);            String verdict = sensitive ? "LEAK (sensitive name)"                    : allowed.contains(field) ? "ok" : "REMOVE (not in the contract)";            System.out.printf("  %-13s %s%n", field, verdict);        }    }
    public static void main(String[] args) {        Map<String, Object> entityBody = new LinkedHashMap<>();        entityBody.put("email", "asha.rao@example.com");        entityBody.put("passwordHash", "{bcrypt}$2a$10$tf36...");        entityBody.put("id", 2);        entityBody.put("enabled", true);        entityBody.put("createdAt", "2026-10-16T13:53:29");        entityBody.put("roles", List.of("CUSTOMER"));
        Set<String> contract = Set.of("id", "email", "fullName", "customerId", "roles");        review("GET /api/v1/me (entity)", entityBody, contract);    }}
Output
GET /api/v1/me (entity)
  email         ok
  passwordHash  LEAK (sensitive name)
  id            ok
  enabled       LEAK (sensitive name)
  createdAt     REMOVE (not in the contract)
  roles         ok

What this code does

  • Two checks per field: a deny-list of dangerous words, and the contract's allow-list for this endpoint. Either one alone misses something.
  • createdAt is not secret, but it is not in the contract, so it goes: every extra field is something clients may start to depend on.
  • The input is the real body from Example 1. In a real review you paste the JSON of each endpoint, for each role, into a list like this.

Run the review in four steps:

  • Call the endpoint as each role (guest, customer, admin) and save the bodies.
  • List every field and write next to it who needs it.
  • Remove what nobody needs; mask what only needs a hint (last 4 digits).
  • Trigger the errors too: 400, 404, 409 and a forced 500.

Red flags: anything named like password, hash, token, secret; internal flags such as enabled or failedLogins; ids of other users; full card or phone numbers where the last digits are enough; and every field of an error body except type, title, status, detail and instance.

Next step

Check your understanding

11 quick questions