Video in progress

Strong Middle 🌱 Spring

One endpoint has to accept a card or a cash payment with different fields. How do you accept polymorphic JSON with Jackson, and what is the risk?

On the common interface you list the allowed types with @JsonTypeInfo(use = Id.NAME, property = "type") and @JsonSubTypes; Jackson creates the right class based on the type field. Never allow creating arbitrary types by the class name in the JSON, which is a source of well-known RCE vulnerabilities.

📖 Answer

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = CardPayment.class, name = "CARD"),
    @JsonSubTypes.Type(value = CashPayment.class, name = "CASH")
})
sealed interface PaymentRequest permits CardPayment, CashPayment {}

record CardPayment(@NotBlank String cardToken, @Positive BigDecimal amount) implements PaymentRequest {}
record CashPayment(@NotBlank String cashierId, @Positive BigDecimal amount) implements PaymentRequest {}
@PostMapping("/api/payments")
PaymentResult pay(@Valid @RequestBody PaymentRequest req) {
    return switch (req) {
        case CardPayment c -> cardService.pay(c);
        case CashPayment c -> cashService.pay(c);
    };
}

In Java 21, sealed + a pattern matching switch fit this very well: if you add a new type, the compiler forces you to update the switches that have no default.

If {"type":"CRYPTO", ...} arrives, Jackson throws InvalidTypeIdException, and Spring wraps it in HttpMessageNotReadableException and returns 400. Give the client a clear message in the advice. And @Valid checks the annotations of the actual runtime type.

The dangerous side is Id.CLASS or ObjectMapper.activateDefaultTyping(...). With them the object is created from the full class name inside the JSON, and an attacker can execute code through "gadget" classes on the classpath. Many of Jackson's CVEs come from exactly this. For an external API, use only Id.NAME with an explicit list.

Small traps: the type field also appears in the response, so agree on that with the frontend; and polymorphism has to be documented separately in the OpenAPI spec (oneOf + discriminator).