Video in progress
How do you deserialize polymorphic objects from JSON, and what security traps are there?
In Jackson you give a logical type name ("type": "card") with @JsonTypeInfo(use = Id.NAME) and @JsonSubTypes. Taking the class name from the JSON (Id.CLASS, global default typing) is dangerous: an attacker can instantiate any "gadget" class on the classpath.
📖 Answer
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = CardPayment.class, name = "card"),
@JsonSubTypes.Type(value = BankTransfer.class, name = "bank")
})
public sealed interface PaymentMethod permits CardPayment, BankTransfer {}
public record CardPayment(String token) implements PaymentMethod {}
public record BankTransfer(String iban) implements PaymentMethod {}
The request:
{ "type": "card", "token": "tok_123" }
Only the listed classes get created here: it's an allowlist.
Dangerous variants:
@JsonTypeInfo(use = Id.CLASS): the JSON carries"@class": "com.zaif.Gadget";objectMapper.enableDefaultTyping()(deprecated) or an unrestrictedactivateDefaultTyping. Many CVEs in Jackson's history come from exactly this. If you really need it, restrict the packages withBasicPolymorphicTypeValidator.
From a design point of view:
- type names are part of the API contract. Renaming a class must not change them, so use
Id.NAMEwith explicit names; - decide what happens when an unknown
typearrives: a 400 error, or an "unknown" type throughdefaultImpl; - if the type can be determined from a unique set of fields, since Jackson 2.12 there is also
Id.DEDUCTION, but it's brittle: adding a new field can introduce ambiguity.
The same rules apply to JSON in Kafka messages and in caches.
Sign up to mark studied questions and save your progress.