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

feature: add LogsafeArgName errorprone rule #1459

Merged
merged 4 commits into from
Jul 29, 2020
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -190,6 +190,7 @@ Safe Logging can be found at [github.com/palantir/safe-logging](https://github.c
- `ImmutablesStyleCollision`: Prevent unintentionally voiding immutables Style meta-annotations through the introduction of inline style annotations.
- `TooManyArguments`: Prefer Interface that take few arguments rather than many.
- `PreferStaticLoggers`: Prefer static loggers over instance loggers.
- `LogsafeArgName`: Prevent certain named arguments as being logged as safe. Specify unsafe argument names using `LogsafeArgName:UnsafeArgNames` errorProne flag.

### Programmatic Application

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* (c) Copyright 2020 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.auto.service.AutoService;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.ErrorProneFlags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.CompileTimeConstantExpressionMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.tree.JCTree;
import java.util.List;
import java.util.Set;

@AutoService(BugChecker.class)
@BugPattern(
name = "LogsafeArgName",
link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks",
linkType = BugPattern.LinkType.CUSTOM,
providesFix = BugPattern.ProvidesFix.REQUIRES_HUMAN_ATTENTION,
severity = SeverityLevel.ERROR,
summary = "Prevent certain argument names from being logged as safe.")
public final class LogsafeArgName extends BugChecker implements MethodInvocationTreeMatcher {
static final String UNSAFE_ARG_NAMES_FLAG = "LogsafeArgName:UnsafeArgNames";

private static final Matcher<ExpressionTree> SAFE_ARG_OF =
Matchers.staticMethod().onClass("com.palantir.logsafe.SafeArg").named("of");
private final Matcher<ExpressionTree> compileTimeConstExpressionMatcher =
new CompileTimeConstantExpressionMatcher();

private final Set<String> unsafeParamNames;

// Must have default constructor for service loading to work correctly
public LogsafeArgName() {
this.unsafeParamNames = ImmutableSet.of();
}

public LogsafeArgName(ErrorProneFlags flags) {
this.unsafeParamNames =
flags.getList(UNSAFE_ARG_NAMES_FLAG).map(ImmutableSet::copyOf).orElseGet(ImmutableSet::of);
}

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (unsafeParamNames.isEmpty() || !SAFE_ARG_OF.matches(tree, state)) {
return Description.NO_MATCH;
}

List<? extends ExpressionTree> args = tree.getArguments();
ExpressionTree argNameExpression = args.get(0);
if (compileTimeConstExpressionMatcher.matches(argNameExpression, state)) {
String argName = (String) ((JCTree.JCLiteral) argNameExpression).getValue();
if (unsafeParamNames.stream().anyMatch(unsafeArgName -> unsafeArgName.equalsIgnoreCase(argName))) {
SuggestedFix.Builder builder = SuggestedFix.builder();
String unsafeArg = SuggestedFixes.qualifyType(state, builder, "com.palantir.logsafe.UnsafeArg");
return buildDescription(tree)
.setMessage("Arguments with name '" + argName + "' must be marked as unsafe.")
.addFix(builder.replace(tree.getMethodSelect(), unsafeArg + ".of")
.build())
.build();
}
}

return Description.NO_MATCH;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* (c) Copyright 2020 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.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.ErrorProneFlags;
import org.junit.jupiter.api.Test;

public final class LogsafeArgNameTest {

@Test
public void catches_unsafe_arg_name() {
getCompilationHelper()
.addSourceLines(
"Test.java",
"import com.palantir.logsafe.SafeArg;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: must be marked as unsafe",
" SafeArg.of(\"foo\", 1);",
" }",
"",
"}")
.doTest();
}

@Test
public void catches_case_insensitive_unsafe_arg_name() {
getCompilationHelper()
.addSourceLines(
"Test.java",
"import com.palantir.logsafe.SafeArg;",
"class Test {",
" void f() {",
" // BUG: Diagnostic contains: must be marked as unsafe",
" SafeArg.of(\"Foo\", 1);",
" }",
"",
"}")
.doTest();
}

@Test
public void fixes_unsafe_arg_name() {
getRefactoringHelper()
.addInputLines(
"Test.java",
"import com.palantir.logsafe.SafeArg;",
"class Test {",
" void f() {",
" SafeArg.of(\"Foo\", 1);",
" }",
"",
"}")
.addOutputLines(
"Test.java",
"import com.palantir.logsafe.SafeArg;",
"import com.palantir.logsafe.UnsafeArg;",
"class Test {",
" void f() {",
" UnsafeArg.of(\"Foo\", 1);",
" }",
"",
"}")
.doTest();
}

@Test
public void ignores_safe_arg_names() {
getCompilationHelper()
.addSourceLines(
"Test.java",
"import com.palantir.logsafe.SafeArg;",
"class Test {",
" void f() {",
" SafeArg.of(\"baz\", 1);",
" }",
"",
"}")
.doTest();
}

private static RefactoringValidator getRefactoringHelper() {
return RefactoringValidator.of(
new LogsafeArgName(ErrorProneFlags.builder()
.putFlag(LogsafeArgName.UNSAFE_ARG_NAMES_FLAG, "foo,bar")
.build()),
LogsafeArgNameTest.class);
}

private static CompilationTestHelper getCompilationHelper() {
return CompilationTestHelper.newInstance(LogsafeArgName.class, LogsafeArgNameTest.class)
.setArgs(ImmutableList.of("-XepOpt:" + LogsafeArgName.UNSAFE_ARG_NAMES_FLAG + "=foo,bar"));
}
}
6 changes: 6 additions & 0 deletions changelog/@unreleased/pr-1459.v2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
type: feature
feature:
description: add LogsafeArgName errorprone rule which allows users to specify a
list of argument names that must always be tagged as unsafe.
links:
- https://github.com/palantir/gradle-baseline/pull/1459
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,15 @@ public class BaselineErrorProneExtension {
// Baseline checks
"BracesRequired",
"CatchBlockLogException",
"CollectionStreamForEach",
// TODO(ckozak): re-enable pending scala check
// "CatchSpecificity",
"ExtendsErrorOrThrowable",
"CollectionStreamForEach",
"ExecutorSubmitRunnableFutureIgnored",
"ExtendsErrorOrThrowable",
"FinalClass",
"LambdaMethodReference",
"LoggerEnclosingClass",
"LogsafeArgName",
"OptionalFlatMapOfNullable",
"OptionalOrElseMethodInvocation",
"PreferBuiltInConcurrentKeySet",
Expand Down