Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DangerousIdentityKey identifies unsafe map and set keys #1731

Merged
merged 7 commits into from
Apr 17, 2021
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ Safe Logging can be found at [github.com/palantir/safe-logging](https://github.c
- `ClassInitializationDeadlock`: Detect type structures which can cause deadlocks initializing classes.
- `ConsistentLoggerName`: Ensure Loggers are named consistently.
- `PreferImmutableStreamExCollections`: It's common to use toMap/toSet/toList() as the terminal operation on a stream, but would be extremely surprising to rely on the mutability of these collections. Prefer `toImmutableMap`, `toImmutableSet` and `toImmutableList`. (If the performance overhead of a stream is already acceptable, then the `UnmodifiableFoo` wrapper is likely tolerable).
- `DangerousIdentityKey`: Key type does not override equals() and hashCode, so comparisons will be done on reference equality only.

### Programmatic Application

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* (c) Copyright 2021 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.baseline.errorprone;

import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.AbstractAsKeyOfSetOrMap;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.util.Name;

/**
* Warns that users should not have a {@link java.util.regex.Pattern} as a key to a Set or Map.
*/
@BugPattern(
name = "DangerousIdentityKey",
summary = "Key type does not override equals() and hashCode, so comparisons will be done on"
+ " reference equality only. If neither deduplication nor lookup are needed,"
+ " consider using a List instead. Otherwise, use IdentityHashMap/Set,"
+ " or an Iterable/List of pairs.",
severity = SeverityLevel.WARNING)
public final class DangerousIdentityKey extends AbstractAsKeyOfSetOrMap {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we try to push this upstream to error-prone proper? I'm curious if there is a reason they haven't added something of this shape (though this is the type of thing drilled fairly well by Effective Java, I'd like to have 🤖 compiler assistance).

I can add a test case to confirm that this catches the construction in places like stream collectors, as that's where I noticed one example.

Also worth noting that since we're building on AbstractAsKeyOfSetOrMap it is specific to the actual constructed map/set type (not the apparent type of say Map<Pattern, String>) and analyzes the typical JDK & Guava (minus WeakHash(Map|Set)) hash based maps & sets where hashCode and equals are relevant. Not sure if we need/want a similar check for Caffeine caches & sorted/navigable map & set types. Reminds me of some places I've seen java.net.URL as keys 😢 .

https://github.com/google/error-prone/blob/c601758e81723a8efc4671726b8363be7a306dce/core/src/main/java/com/google/errorprone/bugpatterns/AbstractAsKeyOfSetOrMap.java#L43-L91

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good point, this should be a strong candidate for an upstream contribution, although I've never had much luck with error-prone contributions, I can reach out again.

We could extend AbstractAsKeyOfSetOrMap to include caches (guava + caffeine) as well as collectors. I can PR something here shortly, and make a similar contribution to the abstract class upstream.


@Override
protected boolean isBadType(Type type, VisitorState state) {
// Only flag final types, otherwise we'll encounter false positives when presented with overrides.
if (type == null || !type.isFinal()) {
return false;
}
return !implementsMethod(state.getTypes(), type, state.getNames().equals, state)
|| !implementsMethod(state.getTypes(), type, state.getNames().hashCode, state);
}

private static boolean implementsMethod(Types types, Type type, Name methodName, VisitorState state) {
MethodSymbol equals =
(MethodSymbol) state.getSymtab().objectType.tsym.members().findFirst(methodName);
return !Iterables.isEmpty(types.membersClosure(type, false)
.getSymbolsByName(methodName, m -> m != equals && m.overrides(equals, type.tsym, types, false)));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.baseline.errorprone;

import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public final class DangerousIdentityKeyTest {

private CompilationTestHelper compilationHelper;

@BeforeEach
public void before() {
compilationHelper = CompilationTestHelper.newInstance(DangerousIdentityKey.class, getClass());
}

@Test
public void testInvalidMapKey() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"import java.util.regex.Pattern;",
"class Test {",
" private Object test() {",
" // BUG: Diagnostic contains: does not override equals",
" return new HashMap<Pattern, String>();",
" }",
"}")
.doTest();
}

@Test
public void testInvalidSetKey() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"import java.util.regex.Pattern;",
"class Test {",
" private Object test() {",
" // BUG: Diagnostic contains: does not override equals",
" return new HashSet<Pattern>();",
" }",
"}")
.doTest();
}

@Test
public void testValidMap() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"import java.util.regex.Pattern;",
"class Test {",
" private Object test() {",
" return new IdentityHashMap<Pattern, String>();",
" }",
"}")
.doTest();
}

@Test
public void testValidSetKey() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"class Test {",
" private Object test() {",
" return new HashSet<String>();",
" }",
"}")
.doTest();
}

@Test
public void testValidNonFinal() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"class Test {",
" static class Impl {}",
" private Object test() {",
" return new HashSet<Impl>();",
" }",
"}")
.doTest();
}

@Test
public void testValidEnum() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"class Test {",
" enum Impl {",
" INSTANCE",
" }",
" private Object test() {",
" return new HashSet<Impl>();",
" }",
"}")
.doTest();
}

@Test
public void testInvalidNoEquals() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"class Test {",
" static final class Impl {",
" @Override public boolean equals(Object o) {",
" return true;",
" }",
" }",
" private Object test() {",
" // BUG: Diagnostic contains: does not override",
" return new HashSet<Impl>();",
" }",
"}")
.doTest();
}

@Test
public void testInvalidNoHash() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"class Test {",
" static final class Impl {",
" @Override public int hashCode() {",
" return 1;",
" }",
" }",
" private Object test() {",
" // BUG: Diagnostic contains: does not override",
" return new HashSet<Impl>();",
" }",
"}")
.doTest();
}

@Test
public void testObjectAllowed() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"class Test {",
" private Object test() {",
" return new HashSet<Object>();",
" }",
"}")
.doTest();
}

@Test
public void testRawTypeAllowed() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"class Test {",
" private Object test() {",
" return new HashSet();",
" }",
"}")
.doTest();
}

@Test
public void testWildcardAllowed() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"class Test {",
" private HashSet<?> test() {",
" return new HashSet<>();",
" }",
"}")
.doTest();
}

@Test
void testCollectMapInvalidKey() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"import java.util.regex.Pattern;",
"import java.util.stream.*;",
"class Test {",
" private Map<Pattern, String> test() {",
" // BUG: Diagnostic contains: does not override",
" return Stream.of(\".\").collect(",
" Collectors.toMap(Pattern::compile, s -> s));",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right now we don't actually catch this case

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#1733 will handle this

" }",
"}")
.doTest();
}

@Test
void testCollectMapValidKey() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"import java.util.regex.Pattern;",
"import java.util.stream.*;",
"class Test {",
" private Map<String, Pattern> test() {",
" return Stream.of(\".\").collect(",
" Collectors.toMap(s -> s, Pattern::compile));",
" }",
"}")
.doTest();
}
}
5 changes: 5 additions & 0 deletions changelog/@unreleased/pr-1731.v2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
type: improvement
improvement:
description: DangerousIdentityKey identifies key types which do not override equals or hashCode thus rely on reference comparison.
links:
- https://github.com/palantir/gradle-baseline/pull/1731