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

Add template rule: ObfuscationRequired #69

Merged
merged 1 commit into from
Feb 6, 2022
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
8 changes: 7 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@
<sonar.version>3.4.0.905</sonar.version>
<commons-logging.version>1.2</commons-logging.version>
<!-- General dependencies -->
<pmd.rules.version>6.41.0</pmd.rules.version>
<pmd.rules.version>6.42.0</pmd.rules.version>
<cactoos.version>0.50</cactoos.version>
<!-- Testing -->
<hamcrest.version>2.2</hamcrest.version>
Expand Down Expand Up @@ -184,6 +184,12 @@
<version>2.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.35</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
Expand Down
163 changes: 163 additions & 0 deletions src/main/java/io/github/dgroup/arch4u/pmd/ObfuscationRequired.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
/*
* MIT License
*
* Copyright (c) 2019-2022 Yurii Dubinka
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/

package io.github.dgroup.arch4u.pmd;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import net.sourceforge.pmd.lang.ast.AbstractNode;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTArgumentList;
import net.sourceforge.pmd.lang.java.ast.ASTArguments;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTName;
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
import net.sourceforge.pmd.lang.java.ast.ASTType;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
import net.sourceforge.pmd.lang.java.symboltable.JavaNameOccurrence;
import net.sourceforge.pmd.lang.java.xpath.TypeIsFunction;
import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;

/**
* A rule that prohibits the using methods of a particular class.
*
* @see <a href="https://github.com/dgroup/arch4u-pmd/issues/22">https://github.com/dgroup/arch4u-pmd/issues/22</a>
* @since 0.1.0
*/
@SuppressWarnings("PMD.StaticAccessToStaticFields")
public final class ObfuscationRequired extends AbstractJavaRule {

/**
* Property descriptor with test class suffix.
*/
private static final PropertyDescriptor<List<String>> LOGGERS =
PropertyFactory.stringListProperty("loggerClasses")
.desc("The fully qualified name of the class for logging")
.defaultValues(
"org.slf4j.Logger",
"java.util.logging.Logger",
"org.apache.log4j.Logger",
"org.apache.logging.log4j.Logger"
)
.build();

/**
* Property descriptor with the list of the prohibited methods.
*/
private static final PropertyDescriptor<List<String>> SENSITIVE =
PropertyFactory.stringListProperty("sensitiveClasses")
.desc("List of prohibited methods")
.emptyDefaultValue()
.build();

/**
* Constructor for defining property descriptor.
*/
@SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors")
public ObfuscationRequired() {
this.definePropertyDescriptor(LOGGERS);
this.definePropertyDescriptor(SENSITIVE);
}

@Override
public Object visit(final ASTVariableDeclaratorId vardecl, final Object data) {
if (this.isLogger(vardecl.getTypeNode())) {
for (final NameOccurrence usage : vardecl.getUsages()) {
final JavaNameOccurrence occurrence = (JavaNameOccurrence) usage;
getArguments(occurrence)
.stream()
.filter(this::isSensitiveData)
.forEach(arg -> this.addViolation(data, arg));
}
}
return data;
}

/**
* Checks if the provided type is logger.
* @param type Type node.
* @return True if the type is logger.
*/
private boolean isLogger(final ASTType type) {
return this.getProperty(LOGGERS)
.stream()
.anyMatch(logger -> TypeIsFunction.typeIs(type, logger));
}

/**
* Gets argument of logger invocation.
* @param occurrence Name occurrence.
* @return List of arguments as expressions.
*/
private static List<ASTExpression> getArguments(final JavaNameOccurrence occurrence) {
return Optional.ofNullable(occurrence.getLocation())
.map(loc -> loc.getFirstParentOfType(ASTPrimaryExpression.class))
.map(prex -> prex.getFirstChildOfType(ASTPrimarySuffix.class))
.map(suf -> suf.getFirstChildOfType(ASTArguments.class))
.map(args -> args.getFirstChildOfType(ASTArgumentList.class))
.map(arglist -> arglist.findChildrenOfType(ASTExpression.class))
.orElse(Collections.emptyList());
}

/**
* Checks if the object has sensitive data. In this case it's not allowed
* to log it without applying obfuscation.
* @param argument Expression node, logger argument.
* @return True if the argument contains sensitive data.
*/
private boolean isSensitiveData(final ASTExpression argument) {
final Node node;
if (hasDirectToStringInvocation(argument)) {
node = argument.getFirstChildOfType(ASTPrimaryExpression.class)
.getFirstChildOfType(ASTPrimaryPrefix.class);
} else {
node = argument;
}
return this.getProperty(SENSITIVE)
.stream()
.anyMatch(clss -> TypeIsFunction.typeIs(node, clss));
}

/**
* Checks if the expression has direct {@code toString} invocation.
* In this case, the type should be checked for PrimaryExpression/PrimaryPrefix node.
* @param expression Expression node, logger argument.
* @return True if there is {@code toString} invocation.
*/
private static boolean hasDirectToStringInvocation(final ASTExpression expression) {
return Optional.ofNullable(expression.getFirstChildOfType(ASTPrimaryExpression.class))
.map(prex -> prex.getFirstChildOfType(ASTPrimaryPrefix.class))
.map(prefix -> prefix.getFirstChildOfType(ASTName.class))
.map(AbstractNode::getImage)
.filter(img -> img.endsWith(".toString"))
.isPresent();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,36 @@
</example>
</rule>

<rule name="ObfuscationRequired"
since="0.1.0"
language="java"
message="TBD"
class="io.github.dgroup.arch4u.pmd.ObfuscationRequired">
<description>
TBD
</description>
<priority>3</priority>
<properties>
<property name="loggerClasses" delimiter="|" value="org.slf4j.Logger
|java.util.logging.Logger
|org.apache.log4j.Logger
|org.apache.logging.log4j.Logger"/>
<property name="sensitiveClasses" value="io.github.dgroup.arch4u.pmd.test_entity.Person"/>
</properties>
<example>
<![CDATA[
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.dgroup.arch4u.pmd.test_entity.Person;
class Foo {
Logger logger = LoggerFactory.getLogger(Foo.class);

void bar(Person person) {
logger.info("Processing started for customer {}", person);
}
}
]]>
</example>
</rule>

</ruleset>
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* MIT License
*
* Copyright (c) 2019-2022 Yurii Dubinka
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/

package io.github.dgroup.arch4u.pmd;

import net.sourceforge.pmd.testframework.SimpleAggregatorTst;

/**
* Test case for {@link ObfuscationRequired} rule.
*
* @since 0.1.0
*/
@SuppressWarnings({"PMD.TestClassWithoutTestCases", "PMD.JUnit4TestShouldUseBeforeAnnotation"})
public final class ObfuscationRequiredTest extends SimpleAggregatorTst {

@Override
public void setUp() {
addRule(
"io/github/dgroup/arch4u/pmd/arch4u-template-ruleset.xml",
"ObfuscationRequired"
);
}
}
47 changes: 47 additions & 0 deletions src/test/java/io/github/dgroup/arch4u/pmd/test_entity/Person.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* MIT License
*
* Copyright (c) 2019-2022 Yurii Dubinka
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/

package io.github.dgroup.arch4u.pmd.test_entity;

/**
* Test entity with sensitive data.
* @see io.github.dgroup.arch4u.pmd.ObfuscationRequired
* @since 0.1.0
* @checkstyle MemberNameCheck (200 lines)
* @checkstyle DesignForExtensionCheck (200 lines)
* @checkstyle StringLiteralsConcatenationCheck (200 lines)
*/
public class Person {
/**
* Some test field.
*/
private String sensitiveData;

@Override
public String toString() {
return "Person{"
+ "sensitiveData='" + sensitiveData + '\''
+ '}';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* MIT License
*
* Copyright (c) 2019-2022 Yurii Dubinka
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/

/**
* Test enities for the {@link io.github.dgroup.arch4u.pmd} package.
*
* @author Oleksii Dykov ([email protected])
* @since 0.1.0
*/
package io.github.dgroup.arch4u.pmd.test_entity;
Loading