Card 03/ 06
Missing @Valid: Constraint Annotations That Check Nothing
Leave one annotation off the parameter and invalid data reaches your code with a 200.
Constraint annotations such as @NotBlank are only checked when something asks for them, and in a controller that is @Valid on the parameter. Leave @Valid off and every constraint on the class silently stops applying.
A RideRequest record whose pickup field is @NotBlank and whose passengers field is @Min(1), a body that breaks both rules, and a parameter without @Valid:
@PostMapping("/rides")
ResponseEntity<String> createRide(@RequestBody RideRequest request) {
return ResponseEntity.ok("created without validation: " + request);
}POST /rides, body {"pickup":"","passengers":0}
-> 200 created without validation: RideRequest[pickup=, passengers=0]The constraints on RideRequest have not changed. The request went straight to the method with an empty pickup and zero passengers, and the handler answered 200. Spring only runs the validator for parameters that ask for it with @Valid (or Spring's own @Validated); every other parameter is converted and passed on as it is.
It is easy to miss in review, because a record with @NotBlank on its fields looks validated on its own. It is expensive, because the invalid data travels on into the database, or into business rules that assumed it had been checked.
Put @Valid on every @RequestBody parameter whose class carries constraints, and write one test per endpoint that sends an invalid body and expects 400. That test fails the day someone removes the annotation.
← → move through sections and cards