secuf
secuf

Reputation: 35

Malicious code vulnerability - May expose internal representation by returning reference to mutable object - With what objects?

I'm getting the following violation reported by Sonar: May expose internal representation by returning reference to mutable object.

It's because I'm returning a String[] from a getter.

I know what the problem is and how to solve it but going through several thread on stackoverflow I noticed that seems to be happen for String[] and Dates for example:

Malicious code vulnerability - May expose internal representation by returning reference to mutable object

Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object

But given the reason why that happens which is returning a reference to an object whose internal state could be changed by the caller. Shouldn't that violation be raised for every getter returning a mutable object?

For example:

public List<String> getList() { return list; }

public Foo getFoo() { return foo; } //where foo is just a random object with getters and setters...

The caller could change the state of the returned objects. Shouldn't sonar report the same for those?

Many thanks, Francisco.

Upvotes: 1

Views: 6573

Answers (1)

JB Nizet
JB Nizet

Reputation: 691835

Sonar is not smart enough to know if an object is mutable or not. Especially if you're returning a List, it can't tell if what you're actually returning is an ArrayList, an ImmutableList or an unmodifiable list. So it doesn't emit any warning to avoid flooding you with false positives.

Arrays and Date, on the other hand, are well-known standard classes that are mutable, and for which it can safely emist this warning.

Upvotes: 4

Related Questions