Video in progress

Strong Middle 🧱 OOP and SOLID

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 unrestricted activateDefaultTyping. Many CVEs in Jackson's history come from exactly this. If you really need it, restrict the packages with BasicPolymorphicTypeValidator.

From a design point of view:

  • type names are part of the API contract. Renaming a class must not change them, so use Id.NAME with explicit names;
  • decide what happens when an unknown type arrives: a 400 error, or an "unknown" type through defaultImpl;
  • 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.