Quick revision
The short answer
The real fix is to stop serializing domain or persistence objects directly and return a response DTO, often a record, that contains only the fields the client may see. As an immediate patch, we hide the sensitive fields with transient or an exclusion strategy, and we treat anything already exposed as leaked and rotate or reset it. To prevent recurrence, we prefer allow-list models (DTOs or @Expose) over block-lists, and add tests that serialize every response type and fail on forbidden field names; DTOs are also cleaner than transient, which affects Java serialization and JPA too.
What to remember
In this answer, we saw that serializing an entity directly makes every field public, so passwordHash and internal flags leaked. We contained it with an exclusion strategy, avoiding the transient keyword because JPA would stop persisting the field, and treated the exposed hashes as leaked. The lasting fix is a response DTO, an allow-list where new fields are hidden by default, backed by tests that fail on forbidden field names and a rule that controllers never return entities.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The real fix is to stop serializing domain or persistence objects directly and return a response DTO, often a record, that contains only the fields the client may see. As an immediate patch, we hide the sensitive fields with transient or an exclusion strategy, and we treat anything already exposed as leaked and rotate or reset it. To prevent recurrence, we prefer allow-list models (DTOs or @Expose) over block-lists, and add tests that serialize every response type and fail on forbidden field names; DTOs are also cleaner than transient, which affects Java serialization and JPA too.
Why this question is asked
This finding is common and serious. When an entity is serialized as is, every field anyone adds to it later becomes part of the public API, including password hashes, internal fraud flags and audit columns. The security review found two such fields today; the design guarantees more tomorrow. Interviewers ask this scenario to see whether we handle the incident properly, fix the design rather than just the symptom, and put a guard in place. In this answer, we will see why the leak happens, contain it, design the proper response model, explain why allow-lists beat block-lists, and add automated checks so it cannot come back.
1Why the Fields Leak
Gson's reflective adapter writes every non-static, non-transient field of an object. When a controller returns the User entity, Gson has no idea which fields are meant for the client; it simply writes them all.
The underlying mistake is that one class serves two purposes: it describes how a user is stored, and it is also used to describe what the API returns. Those two shapes change for different reasons, and every change to the storage shape silently changes the API.
2Contain the Incident
First we stop the bleeding. The fastest safe patch is to hide the two fields in the serialized output, for example with an ExclusionStrategy on the shared Gson instance that skips passwordHash and internalFlagged, or with a small annotation-based rule. We deploy that immediately.
There is a trap in the most obvious patch. Marking passwordHash with the transient keyword hides it from Gson, but transient is also read by JPA, which treats transient fields as not persistent. On an entity, that change would stop the hash being saved, and the next password change would be lost. So on entities we use an exclusion strategy or Gson's own mechanisms, never the transient keyword.
Then we treat the exposed data as leaked. Password hashes can be attacked offline, so depending on the hash algorithm and how long the exposure lasted, we force password resets for affected users, check access logs for who called the endpoint, and follow the company's incident process, which may include notifying users. Internal flags are less sensitive but may reveal fraud rules, so the fraud team should know.
3Return a Response DTO
The durable fix is a separate class for the response, a DTO (data transfer object), whose only job is to define what the API returns. A record is ideal: it is short, immutable and has exactly the fields we list.
- HTTP responseJSON written from
UserResponse - UserResponse recordonly fields the client may see
- Mapping in the service
UserResponse.from(user) - User entitystorage shape, may include secrets
4 layers, from the top down. Step through them one at a time.
The entity never reaches the serializer, so a new secret field cannot leak.
Notice what changed. The entity can gain any number of new fields, and the response does not change until someone edits UserResponse, in a pull request that reviewers can see. The response also stops depending on lazy-loaded relations and persistence details, which removes a separate class of bugs.
4Why Allow-Lists Beat Block-Lists
Excluding passwordHash and internalFlagged is a block-list: we name the fields that must not leak. Its weakness is that it protects only against the risks we have already thought of. The next developer who adds a twoFactorSecret field to User has to remember to block it, and if they forget, it leaks.
A DTO, or Gson's @Expose with excludeFieldsWithoutExposeAnnotation(), is an allow-list: we name the fields that may be shown, and everything else is hidden by default. New fields are safe until someone deliberately exposes them. For anything that crosses a trust boundary, that default is the one we want, and DTOs are the cleanest form of it because they do not depend on a builder setting that one stray new Gson() would bypass.
5Tests That Fail on Forbidden Names
Finally, we make the rule checkable. A test serializes every response type the API returns, using the real Gson instance, and fails if any key matches a list of forbidden names or patterns.
The keys helper walks the whole tree, so nested objects are covered too. We add an architecture rule as well, for example with ArchUnit, that controllers must not return types annotated with @Entity. Between the DTO rule and the forbidden-name test, the original mistake would now fail the build twice.
6Follow-up questions
Isn't a DTO for every endpoint a lot of boilerplate?
Records make it small: a one-line declaration plus a mapping method. Mapping libraries such as MapStruct can generate the mapping code if there are many. The cost is low compared with an incident, and DTOs also make API changes explicit in reviews.
Why rotate or reset if the data is only a hash?
Hashes can be attacked offline with guessing, and weak or old algorithms make that cheap. Once a hash has left the service, we cannot know who copied it, so we act as if it was taken. How far we go depends on the algorithm, the exposure window and the logs.
Should the security patch use @Expose instead of an exclusion strategy?
@Expose is a good allow-list, but switching an existing entity to it needs every exposed field annotated and every Gson instance built with excludeFieldsWithoutExposeAnnotation, which takes longer to get right. A targeted exclusion strategy is quicker for the emergency, and the DTO replaces both shortly after.
7Conclusion
In this answer, we saw that serializing an entity directly makes every field public, so passwordHash and internal flags leaked. We contained it with an exclusion strategy, avoiding the transient keyword because JPA would stop persisting the field, and treated the exposed hashes as leaked. The lasting fix is a response DTO, an allow-list where new fields are hidden by default, backed by tests that fail on forbidden field names and a rule that controllers never return entities.
Open with
First I would contain it: deploy a quick patch that hides passwordHash and the internal flags, ideally with an exclusion strategy on the shared Gson instance. I would not use the transient keyword on the entity, because JPA treats transient fields as not persistent, so the hash would stop being saved.
Then, if they want more
In parallel I would treat the exposed data as leaked, check the access logs, and depending on the hash algorithm and exposure window force password resets and follow the incident process. Then I would fix the design. The real mistake is serializing a persistence object directly, so every field ever added to User becomes part of the API.
I would return a response DTO, typically a record like UserResponse with id, email and admin, built by a small mapping method. That is an allow-list: new fields on the entity stay hidden until someone deliberately adds them to the DTO, which is visible in review. Block-lists, like excluding named fields, only protect against risks we already thought of.
To prevent recurrence, I would add a test that serializes every response type with the real Gson and fails on keys matching patterns like password, secret, token or internal, plus an ArchUnit rule that controllers never return @Entity types.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A security review found that a User object serialized with Gson in API responses...": https://scrivio-interview-library.netlify.app/java/json-libraries/4702b319b4/