Java

Java

Made by DeepSource

Persistent objects should not be returned from methods JAVA-S1066

Security
Critical
a06 a04 cwe-201 owasp top 10 cwe-212

Returning persistent objects from methods should be avoided as much as possible.

APIs that allow returning entity objects risk accidentally leaking the application's business logic to the outside world. Even worse, such APIs may enable attackers to tamper with persistent objects by using a loophole in the application's security. For these reasons, it is best to avoid returning entity objects from methods.

Bad Practice

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

// Bad! `Book` is an `@Entity`.
public Book getBook(Long id) {
    return bookRepository.findById(id);
}

Recommended

Use Data Transfer Objects (DTOs) to pass around data between methods/components.

public class BookDTO {
    private Long id;
    private String name;
}

public BookDTO getBook(Long id) {
    Book book = bookRepository.findById(id);
    // Use a utility method to map `@Entity` to a DTO.
    return converToBookDto(book);
}

References

  • OWASP Top Ten (2021) - Category A04 - Insecure Design
  • OWASP Top Ten (2021) - Category A06 - Vulnerable and Outdated Components
  • CWE-212 - Improper Removal of Sensitive Information Before Storage or Transfer
  • CWE-201 - Insertion of Sensitive Information Into Sent Data