Skip to content

Releases: pmd/pmd

PMD 6.1.0 (25-February-2018)

25 Feb 09:30
Compare
Choose a tag to compare

25-February-2018 - 6.1.0

The PMD team is pleased to announce PMD 6.1.0.

This is a minor release.

Table Of Contents

New and noteworthy

Designer UI

The Designer now supports configuring properties for XPath based rule development.
The Designer is still under development and any feedback is welcome.

You can start the designer via run.sh designer or designer.bat.

Fixed Issues

  • all
    • #569: [core] XPath support requires specific toString implementations
    • #795: [cpd] java.lang.OutOfMemoryError
    • #848: [doc] Test failures when building pmd-doc under Windows
    • #872: [core] NullPointerException at FileDataSource.glomName()
    • #854: [ci] Use Java9 for building PMD
  • doc
    • #791: [doc] Documentation site reorganisation
    • #891: [doc] Apex @SuppressWarnings should use single quotes instead of double quotes
    • #909: [doc] Please add new PMD Eclipse Plugin to tool integration section
  • java
    • #825: [java] Excessive*Length ignores too much
    • #888: [java] ParseException occurs with valid '<>' in Java 1.8 mode
    • #920: [java] Update valid identifiers in grammar
  • java-bestpractices
    • #784: [java] ForLoopCanBeForeach false-positive
    • #925: [java] UnusedImports false positive for static import
  • java-design
    • #855: [java] ImmutableField false-positive with lambdas
  • java-documentation
    • #877: [java] CommentRequired valid rule configuration causes PMD error
  • java-errorprone
    • #885: [java] CompareObjectsWithEqualsRule trigger by enum1 != enum2
  • java-performance
    • #541: [java] ConsecutiveLiteralAppends with types other than string
  • scala
    • #853: [scala] Upgrade scala version to support Java 9
  • xml
    • #739: [xml] IllegalAccessException when accessing attribute using Saxon on JRE 9

API Changes

Changes to the Node interface

The method getXPathNodeName is added to the Node interface, which removes the
use of the toString of a node to get its XPath element name (see #569).
A default implementation is provided in AbstractNode, to stay compatible
with existing implementors.

The toString method of a Node is not changed for the time being, and still produces
the name of the XPath node. That behaviour may however change in future major releases,
e.g. to produce a more useful message for debugging.

Changes to CPD renderers

The interface net.sourceforge.pmd.cpd.Renderer has been deprecated. A new interface net.sourceforge.pmd.cpd.renderer.CPDRenderer
has been introduced to replace it. The main difference is that the new interface is meant to render directly to a java.io.Writer
rather than to a String. This allows to greatly reduce the memory footprint of CPD, as on large projects, with many duplications,
it was causing OutOfMemoryErrors (see #795).

net.sourceforge.pmd.cpd.FileReporter has also been deprecated as part of this change, as it's no longer needed.

External Contributions

PMD 6.0.1 (21-January-2018)

21 Jan 15:47
Compare
Choose a tag to compare

21-January-2018 - 6.0.1

The PMD team is pleased to announce PMD 6.0.1.

This is a bug fixing release.

Table Of Contents

Additional information about the new introduced rule categories

With the release of PMD 6.0.0, all rules have been sorted into one of the following eight categories:

  1. Best Practices: These are rules which enforce generally accepted best practices.
  2. Code Style: These rules enforce a specific coding style.
  3. Design: Rules that help you discover design issues.
  4. Documentation: These rules are related to code documentation.
  5. Error Prone: Rules to detect constructs that are either broken, extremely confusing or prone to runtime errors.
  6. Multithreading: These are rules that flag issues when dealing with multiple threads of execution.
  7. Performance: Rules that flag suboptimal code.
  8. Security: Rules that flag potential security flaws.

Please note, that not every category in every language may have a rule. There might be categories with no
rules at all, such as category/java/security.xml, which has currently no rules.
There are even languages, which only have rules of one category (e.g. category/xml/errorprone.xml).

You can find the information about available rules in the generated rule documentation, available
at https://pmd.github.io/pmd-6.0.1/.

In order to help migrate to the new category scheme, the new name for the old, deprecated rule names will
be logged as a warning. See PR #865. Please note, that the deprecated
rule names will keep working throughout PMD 6. You can upgrade to PMD 6 without the immediate need
to migrate your current ruleset. That backwards compatibility will be maintained until PMD 7.0.0 is released.

Fixed Issues

  • all
    • #842: [core] Use correct java bootclasspath for compiling
  • apex-errorprone
    • #792: [apex] AvoidDirectAccessTriggerMap incorrectly detects array access in classes
  • apex-security
    • #788: [apex] Method chaining breaks ApexCRUDViolation
  • doc
    • #782: [doc] Wrong information in the Release Notes about the Security ruleset
    • #794: [doc] Broken documentation links for 6.0.0
  • java
    • #793: [java] Parser error with private method in nested classes in interfaces
    • #814: [java] UnsupportedClassVersionError is failure instead of a warning
    • #831: [java] StackOverflow in JavaTypeDefinitionSimple.toString
  • java-bestpractices
    • #783: [java] GuardLogStatement regression
    • #800: [java] ForLoopCanBeForeach NPE when looping on this object
  • java-codestyle
    • #817: [java] UnnecessaryModifierRule crashes on valid code
  • java-design
    • #785: [java] NPE in DataClass rule
    • #812: [java] Exception applying rule DataClass
    • #827: [java] GodClass crashes with java.lang.NullPointerException
  • java-performance
    • #841: [java] InsufficientStringBufferDeclaration NumberFormatException
  • java-typeresolution
    • #866: [java] rulesets/java/typeresolution.xml lists non-existent rules

API Changes

  • The constant net.sourceforge.pmd.PMD.VERSION has been deprecated and will be removed with PMD 7.0.0.
    Please use net.sourceforge.pmd.PMDVersion.VERSION instead.

External Contributions

PMD 6.0.0 (15-December-2017)

15 Dec 15:07
Compare
Choose a tag to compare

15-December-2017 - 6.0.0

The PMD team is pleased to announce PMD 6.0.0.

This is a major release.

Table Of Contents

New and noteworthy

New Rule Designer

Thanks to Clément Fournier, we now have a new rule designer GUI, which
is based on JavaFX. It replaces the old designer and can be started via

  • bin/run.sh designer (on Unix-like platform such as Linux and Mac OS X)
  • bin\designer.bat (on Windows)

Note: At least Java8 is required for the designer. The old designer is still available
as designerold but will be removed with the next major release.

Java 9 support

The Java grammar has been updated to support analyzing Java 9 projects:

  • private methods in interfaces are possible
  • The underscore "_" is considered an invalid identifier
  • Diamond operator for anonymous classes
  • The module declarations in module-info.java can be parsed
  • Concise try-with-resources statements are supported

Java 9 support is enabled by default. You can switch back to an older java version
via the command line, e.g. -language java -version 1.8.

Revamped Apex CPD

We are now using the Apex Jorje Lexer to tokenize Apex code for CPD. This change means:

  • All comments are now ignored for CPD. This is consistent with how other languages such as Java and Groovy work.
  • Tokenization honors the language specification, which improves accuracy.

CPD will therefore have less false positives and false negatives.

Java Type Resolution

As part of Google Summer of Code 2017, Bendegúz Nagy worked on type resolution
for Java. For this release he has extended support for method calls for both instance and static methods.

Method shadowing and overloading are supported, as are varargs. However, the selection of the target method upon
the presence of generics and type inference is still work in progress. Expect it in forecoming releases.

As for fields, the basic support was in place for release 5.8.0, but has now been expanded to support static fields.

Metrics Framework

As part of Google Summer of Code 2017, Clément Fournier is worked
on the new metrics framework for object-oriented metrics.

There are already a couple of metrics (e.g. ATFD, WMC, Cyclo, LoC) implemented. More metrics are planned.
Based on those metrics, rules like "GodClass" detection could be implemented more easily.
The following rules benefit from the metrics framework: NcssCount (java), NPathComplexity (java),
CyclomaticComplexity (both java and apex).

The Metrics framework has been abstracted and is available in pmd-core for other languages. With this
PMD release, the metrics framework is supported for both Java and Apex.

Error Reporting

A number of improvements on error reporting have taken place, meaning changes to some of the report formats.

Also of note, the xml report now provides a XML Schema definition, allowing easier parsing and validation.

Processing Errors

Processing errors can now provide not only the message previously included on some reports, but also a full stacktrace.
This will allow better error reports when providing feedback to the PMD team and help in debugging issues.

The report formats providing full stacktrace of errors are:

  • html
  • summaryhtml
  • textcolor
  • vbhtml
  • xml
Configuration Errors

For a long time reports have been notified of configuration errors on rules, but they have remained hidden.
On a push to make these more evident to users, and help them get the best results out of PMD, we have started
to include them on the reports.

So far, only reports that include processing errors are showing configuration errors. In other words, the report formats
providing configuration error reporting are:

  • csv
  • html
  • summaryhtml
  • text
  • textcolor
  • vbhtml
  • xml

As we move forward we will be able to detect and report more configuration errors (ie: incomplete auxclasspath)
and include them to such reports.

Apex Rule Suppression

Apex violations can now be suppressed very similarly to how it's done in Java, by making use of a
@SuppressWarnings annotation.

Supported syntax includes:

@SupressWarnings('PMD') // to supress all Apex rules
@SupressWarnings('all') // to supress all Apex rules
@SupressWarnings('PMD.ARuleName') // to supress only the rule named ARuleName
@SupressWarnings('PMD.ARuleName, PMD.AnotherRuleName') // to supress only the rule named ARuleName or AnotherRuleName

Notice this last scenario is slightly different to the Java syntax. This is due to differences in the Apex grammar for annotations.

Rule Categories

All built-in rules have been sorted into one of eight categories:

  1. Best Practices: These are rules which enforce generally accepted best practices.
  2. Code Style: These rules enforce a specific coding style.
  3. Design: Rules that help you discover design issues.
  4. Documentation: These rules are related to code documentation.
  5. Error Prone: Rules to detect constructs that are either broken, extremely confusing or prone to runtime errors.
  6. Multithreading: These are rules that flag issues when dealing with multiple threads of execution.
  7. Performance: Rules that flag suboptimal code.
  8. Security: Rules that flag potential security flaws.

These categories help you to find rules and figure out the relevance and impact for your project.

All rules have been moved accordingly, e.g. the rule "JumbledIncrementer", which was previously defined in the
ruleset "java-basic" has now been moved to the "Error Prone" category. The new rule reference to be used is
<rule ref="category/java/errorprone.xml/JumbledIncrementer"/>.

The old rulesets like "java-basic" are still kept for backwards-compatibility but will be removed eventually.
The rule reference documentation has been updated to reflect these changes.

New Rules

  • The new Java rule NcssCount (category design) replaces the three rules "NcssConstructorCount", "NcssMethodCount",
    and "NcssTypeCount". The new rule uses the metrics framework to achieve the same. It has two properties, to
    define the report level for method and class sizes separately. Constructors and methods are considered the same.

  • The new Java rule DoNotExtendJavaLangThrowable (category errorprone) is a companion for the
    java-strictexception.xml/DoNotExtendJavaLangError, detecting direct extensions of java.lang.Throwable.

  • The new Java rule ForLoopCanBeForeach (category errorprone) helps to identify those for-loops that can
    be safely refactored into for-each-loops available since java 1.5.

  • The new Java rule AvoidFileStream (category performance) helps to identify code relying on FileInputStream / FileOutputStream
    which, by using a finalizer, produces extra / unnecessary overhead to garbage collection, and should be replaced with
    Files.newInputStream / Files.newOutputStream available since java 1.7.

  • The new Java rule DataClass (category design) detects simple data-holders without behaviour. This might indicate
    that the behaviour is scattered elsewhere and the data class exposes the internal data structure,
    which breaks encapsulation.

  • The new Apex rule AvoidDirectAccessTriggerMap (category errorprone) helps to identify direct array access to triggers,
    which can produce bugs by either accessing non-existing indexes, or leaving them out. You should use for-each-loops
    instead.

  • The new Apex rule AvoidHardcodingId (category errorprone) detects hardcoded strings that look like identifiers
    and flags them. Record IDs change between environments, meaning hardcoded ids are bound to fail under a different
    setup.

  • The new Apex rule CyclomaticComplexity (category design) detects overly complex classes and methods. The
    report threshold can be configured separately for classes and methods.

  • A whole bunch of new rules has been added to Apex. They all fit into the category errorprone.
    The 5 rules are migrated for Apex from the equivalent Java rules and include:

    • EmptyCatchBlock to detect catch blocks completely ignoring exceptions.
    • EmptyIfStmt for if blocks with no content, that can be safely removed.
    • EmptyTryOrFinallyBlock for empty try / finally blocks that can be safely removed.
    • EmptyWhileStmt for empty while loops that can be safely removed.
    • EmptyStatementBlock for empty code blocks that can be safely removed.
  • The new Apex rule AvoidSoslInLoops (category performance) is the companion of the old
    AvoidSoqlInLoops rule, flagging SOSL (Salesforce Object Search Language) queries when within
    loops, to avoid governor issues, and hitting the da...

Read more

PMD 5.8.1 (01-July-2017)

01 Jul 17:34
Compare
Choose a tag to compare

01-July-2017 - 5.8.1

The PMD team is pleased to announce PMD 5.8.1.

This is a bug fixing release.

Table Of Contents

Fixed Issues

  • java
    • #471: [java] Error while processing class when EnumMap is used in PMD 5.8.0
    • #477: [core] NoClassDefFoundError under 5.8
    • #478: [core] Processing issues dealing with anonymous classes

API Changes

  • The getGenericArgs() method introduced to TypeNode in 5.8.0 was removed. You can access to generics' info through the JavaTypeDefinition object.
  • The JavaTypeDefinitionBuilder class introduced in 5.8.0 is not more. You can use factory methods available on JavaTypeDefinition

External Contributions

  • #472: [java] fix error with raw types, bug #471

PMD 5.8.0 (24-June-2017)

24 Jun 20:49
Compare
Choose a tag to compare

24-June-2017 - 5.8.0

The PMD team is pleased to announce PMD 5.8.0.

This is a minor release.

Table Of Contents

New and noteworthy

Java Type Resolution

As part of Google Summer of Code 2017, Bendegúz Nagy has been working on completing type resolution for Java.
His progress so far has allowed to properly resolve, in addition to previously supported statements:

  • References to this and super, even when qualified
  • References to fields, even when chained (ie: this.myObject.aField), and properly handling inheritance / shadowing

Lambda parameter types where these are infered rather than explicit are still not supported. Expect future releases to do so.

Metrics Framework

As part of Google Summer of Code 2017, Clément Fournier has been working on
a new metrics framework for object-oriented metrics.

The basic groundwork has been done already and with this release, including a first rule based on the
metrics framework as a proof-of-concept: The rule CyclomaticComplexity, currently in the temporary
ruleset java-metrics, uses the Cyclomatic Complexity metric to find overly complex code.
This rule will eventually replace the existing three CyclomaticComplexity rules that are currently
defined in the java-codesize ruleset (see also issue #445).

Since this work is still in progress, the metrics API (package net.sourceforge.pmd.lang.java.oom)
is not finalized yet and is expected to change.

Modified Rules

  • The Java rule UnnecessaryFinalModifier (ruleset java-unnecessary) now also reports on private methods marked as final.
    Being private, such methods can't be overriden, and therefore, the final keyword is redundant.

  • The Java rule PreserveStackTrace (ruleset java-design) has been relaxed to support the builder pattern on thrown exception.
    This change may introduce some false positives if using the exception in non-orthodox ways for things other than setting the
    root cause of the exception. Contact us if you find any such scenarios.

  • The ruleset java-junit now properly detects JUnit5, and rules are being adapted to the changes on it's API.
    This support is, however, still incomplete. Let us know of any uses we are still missing on the issue tracker

  • The Java rule EmptyTryBlock (ruleset java-empty) now allows empty blocks when using try-with-resources.

  • The Java rule EmptyCatchBlock (ruleset java-empty) now exposes a new property called allowExceptionNameRegex.
    This allow to setup a regular expression for names of exceptions you wish to ignore for this rule. For instance,
    setting it to ^(ignored|expected)$ would ignore all empty catch blocks where the catched exception is named
    either ignored or expected. The default ignores no exceptions, being backwards compatible.

Deprecated Rules

  • The three complexity rules CyclomaticComplexity, StdCyclomaticComplexity, ModifiedCyclomaticComplexity (ruleset java-codesize) have been deprecated. They will be eventually replaced
    by a new CyclomaticComplexity rule based on the metrics framework. See also issue #445.

Fixed Issues

  • General
    • #380: [core] NPE in RuleSet.hashCode
    • #407: [web] Release date is not properly formatted
    • #429: [core] Error when running PMD from folder with space
  • apex
    • #427: [apex] CPD error when parsing apex code from release 5.5.3
  • cpp
    • #431: [cpp] CPD gives wrong duplication blocks for CPP code
  • java
    • #414: [java] Java 8 parsing problem with annotations for wildcards
    • #415: [java] Parsing Error when having an Annotated Inner class
    • #417: [java] Parsing Problem with Annotation for Array Member Types
  • java-design
    • #397: [java] ConstructorCallsOverridableMethodRule: false positive for method called from lambda expression
    • #410: [java] ImmutableField: False positive with lombok
    • #422: [java] PreserveStackTraceRule: false positive when using builder pattern
  • java-empty
    • #413: [java] EmptyCatchBlock don't fail when exception is named ignore / expected
    • #432: [java] EmptyTryBlock: false positive for empty try-with-resource
  • java-imports:
    • #348: [java] imports/UnusedImport rule not considering static inner classes of imports
  • java-junit
    • #428: [java] PMD requires public modifier on JUnit 5 test
    • #465: [java] NullPointerException in JUnitTestsShouldIncludeAssertRule
  • java-logging:
    • #365: [java] InvalidSlf4jMessageFormat does not handle inline incrementation of arguments
  • java-strictexceptions
    • #350: [java] Throwing Exception in method signature is fine if the method is overriding or implementing something
  • java-typeresolution
    • #350: [java] Throwing Exception in method signature is fine if the method is overriding or implementing something
  • java-unnecessary
    • #421: [java] UnnecessaryFinalModifier final in private method
  • jsp
    • #311: [jsp] Parse error on HTML boolean attribute

External Contributions

  • #406: [java] False positive with lambda in java-design/ConstructorCallsOverridableMethod
  • #409: [java] Groundwork for the upcoming metrics framework
  • #416: [java] FIXED: Java 8 parsing problem with annotations for wildcards
  • #418: [java] Type resolution: super and this keywords
  • #423: [java] Add field access type resolution in non-generic cases
  • #425: [java] False positive with builder pattern in java-design/PreserveStackTrace
  • #426: [java] UnnecessaryFinalModifier final in private method
  • #436: [java] Metrics framework tests and various improvements
  • #440: [core] Created ruleset schema 3.0.0 (to use metrics)
  • #443: [java] Optimize typeresolution, by skipping package and import declarations in visit(ASTName)
  • #444: [java] [typeresolution]: add support for generic fields
  • #451: [java] Metrics framework: first metrics + first rule

PMD 5.7.0 (20-May-2017)

20 May 20:47
Compare
Choose a tag to compare

20-Mai-2017 - 5.7.0

The PMD team is pleased to announce PMD 5.7.0.

This is a minor release.

Table Of Contents

New and noteworthy

Modified Rules

  • The rule "FieldDeclarationsShouldBeAtStartOfClass" of the java-design ruleset has a new property ignoreInterfaceDeclarations.
    Setting this property to true ignores interface declarations, that precede fields.
    Example usage:

Renderers

  • Added the 'empty' renderer which will write nothing. Does not affect other behaviors, for example the command line PMD exit status
    will still indicate whether violations were found.

Fixed Issues

  • General
    • #377: [core] Use maven wrapper and upgrade to maven 3.5.0
    • #376: [core] Improve build time on travis
  • java
    • #378: [java] Parser Error for empty statements
  • java-coupling
    • #1427: [java] Law of Demeter violations for the Builder pattern
  • java-design
    • #345: [java] FieldDeclarationsShouldBeAtStartOfClass: Add ability to ignore interfaces
    • #389: [java] RuleSetCompatibility - not taking rename of UnusedModifier into account
  • java-junit
    • #358: [java] Mockito verify method is not taken into account in JUnitTestsShouldIncludeAssert rule
  • java-strings
    • #334: [java] [doc] Add suggestion to use StringUtils#isBlank for InefficientEmptyStringCheck
  • jsp-basic
    • #369: [jsp] Wrong issue "JSP file should use UTF-8 encoding"

API Changes

  • The method net.sourceforge.pmd.util.StringUtil#htmlEncode(String) is deprecated.
    org.apache.commons.lang3.StringEscapeUtils#escapeHtml4(String) should be used instead.

External Contributions

  • #368: [vf] Adding proper AST support for negation expressions
  • #372: [core] Fix XSS in HTML renderer
  • #374: [java] Add property to ignore interfaces in FieldDeclarationsShouldBeAtStartOfClassRule
  • #381: [core] Fix broken link in the site's doc
  • #382: [java] Added documentation details on InefficientEmptyStringCheck
  • #383: [jsp] Fixed JspEncoding false positive
  • #390: [java] Remove trailing whitespaces in design.xml
  • #391: [apex] Fix documentation typo
  • #392: [java] False positive for Law Of Demeter (Builder pattern)
  • #395: [java] Mockito verify method is not taken into account in JUnitTestsShouldIncludeAssert rule

PMD 5.6.1 (29-April-2017)

29 Apr 18:45
Compare
Choose a tag to compare

29-April-2017 - 5.6.1

The PMD team is pleased to announce PMD 5.6.1.

This is a bug fixing release.

Fixed Issues

  • General
    • #363: [core] Rule documentation pages are missing
    • #364: [core] Stream closed exception when running through maven
    • #373: [core] RuleSetFactory - add more helper methods

PMD 5.5.7 (29-April-2017)

29 Apr 20:06
Compare
Choose a tag to compare

29-April-2017 - 5.5.7

The PMD team is pleased to announce PMD 5.5.7.

This is a bug fixing release.

Fixed Issues

  • General
    • #364: [core] Stream closed exception when running through maven

PMD 5.6.0 (22-April-2017)

22 Apr 11:43
Compare
Choose a tag to compare

22-April-2017 - 5.6.0

The PMD team is pleased to announce PMD 5.6.0.

The most significant changes are on analysis performance, support for Salesforce's Visualforce language
a whole new Apex Security Rule Set and the new Braces Rule Set for Apex.

We have added initial support for incremental analysis. The experimental feature allows
PMD to cache analysis results between executions to speed up the analysis for all
languages. New CLI flags and Ant options are available to configure it. Currently
the feature is disabled by default, but this may change as it matures.

Multithread performance has been enhanced by reducing thread-contention on a
bunch of areas. This is still an area of work, as the speedup of running
multithreaded analysis is still relatively small (4 threads produce less
than a 50% speedup). Future releases will keep improving on this area.

Once again, Symbol Table has been an area of great performance improvements.
This time we were able to further improve it's performance by roughly 10% on all
supported languages. In Java in particular, several more improvements were possible,
improving Symbol Table performance by a whooping 80%, that's over 15X faster
than PMD 5.5.1, when we first started working on it.

Java developers will also appreciate the revamp of CloneMethodMustImplementCloneable,
making it over 500X faster, and PreserveStackTrace which is now 7X faster.

Table Of Contents

New and noteworthy

Incremental Analysis

PMD now supports incremental analysis. Analysis results can be cached and reused between runs.
This allows PMD to skip files without violations that have remained unchanged. In future releases,
we plan to extend this behavior to unchanged files with violations too.

The cache is automatically invalidated if:

  • the used PMD version changes
  • the auxclasspath changed and any rules require type resolution
  • the configured rule set has changed

This feature is incubating and is disabled by default. It's only enabled if you
specifically configure a cache file.

To configure the cache file from CLI, a new -cache <path/to/file> flag has been added.

For Ant, a new cacheLocation attribute has been added. For instance:

    <target name="pmd">
        <taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"/>
        <pmd cacheLocation="build/pmd/pmd.cache">
            <ruleset>rulesets/java/design.xml</ruleset>
            <ruleset>java-basic</ruleset>
            <formatter type="xml" toFile="c:\pmd_report.xml"/>
            <fileset dir="/usr/local/j2sdk1.4.1_01/src/">
                <include name="java/lang/*.java"/>
            </fileset>
        </pmd>
    </target>

Visualforce Support

Salesforce developers rejoice. To out growing Apex support we have added full Visualforce support.
Both CPD and PD are available. So far only a security ruleset is available (vf-security).

Visualforce Security Rule Set
VfUnescapeEl

The rule looks for Expression Language occurances printing unescaped values from the backend. These
could lead to XSS attacks.

VfCsrf

The rule looks for <apex:page> tags performing an action on page load, definish such action
through Expression Language, as doing so is vulnerable to CSRF attacks.

Apex Security Rule Set

A new ruleset focused on security has been added, consisting of a wide range of rules
to detect most common security problems.

ApexBadCrypto

The rule makes sure you are using randomly generated IVs and keys for Crypto calls.
Hard-wiring these values greatly compromises the security of encrypted data.

For instance, it would report violations on code such as:

public class without sharing Foo {
    Blob hardCodedIV = Blob.valueOf('Hardcoded IV 123');
    Blob hardCodedKey = Blob.valueOf('0000000000000000');
    Blob data = Blob.valueOf('Data to be encrypted');
    Blob encrypted = Crypto.encrypt('AES128', hardCodedKey, hardCodedIV, data);
}

ApexCRUDViolation

The rule validates you are checking for access permissions before a SOQL/SOSL/DML operation.
Since Apex runs in system mode not having proper permissions checks results in escalation of
privilege and may produce runtime errors. This check forces you to handle such scenarios.

For example, the following code is considered valid:

public class Foo {
    public Contact foo(String status, String ID) {
        Contact c = [SELECT Status__c FROM Contact WHERE Id=:ID];

        // Make sure we can update the database before even trying
        if (!Schema.sObjectType.Contact.fields.Name.isUpdateable()) {
            return null;
        }

        c.Status__c = status;
        update c;
        return c;
    }
}
ApexCSRF

Check to avoid making DML operations in Apex class constructor/init method. This prevents
modification of the database just by accessing a page.

For instance, the following code would be invalid:

public class Foo {
    public init() {
        insert data;
    }

    public Foo() {
        insert data;
    }
}
ApexDangerousMethods

Checks against calling dangerous methods.

For the time being, it reports:

  • Against FinancialForce's Configuration.disableTriggerCRUDSecurity(). Disabling CRUD security
    opens the door to several attacks and requires manual validation, which is unreliable.
  • Calling System.debug passing sensitive data as parameter, which could lead to exposure
    of private data.
ApexInsecureEndpoint

Checks against accessing endpoints under plain http. You should always use
https for security.

ApexOpenRedirect

Checks against redirects to user-controlled locations. This prevents attackers from
redirecting users to phishing sites.

For instance, the following code would be reported:

public class without sharing Foo {
    String unsafeLocation = ApexPage.getCurrentPage().getParameters.get('url_param');
    PageReference page() {
       return new PageReference(unsafeLocation);
    }
}
ApexSharingViolations

Detect classes declared without explicit sharing mode if DML methods are used. This
forces the developer to take access restrictions into account before modifying objects.

ApexSOQLInjection

Detects the usage of untrusted / unescaped variables in DML queries.

For instance, it would report on:

public class Foo {
    public void test1(String t1) {
        Database.query('SELECT Id FROM Account' + t1);
    }
}
ApexSuggestUsingNamedCred

Detects hardcoded credentials used in requests to an endpoint.

You should refrain from hardcoding credentials:

  • They are hard to mantain by being mixed in application code
  • Particularly hard to update them when used from different classes
  • Granting a developer access to the codebase means granting knowledge
    of credentials, keeping a two-level access is not possible.
  • Using different credentials for different environments is troublesome
    and error-prone.

Instead, you should use Named Credentials and a callout endpoint.

For more information, you can check this

ApexXSSFromEscapeFalse

Reports on calls to addError with disabled escaping. The message passed to addError
will be displayed directly to the user in the UI, making it prime ground for XSS
attacks if unescaped.

ApexXSSFromURLParam

Makes sure that all values obtained from URL parameters are properly escaped / sanitized
to avoid XSS attacks.

Apex Braces Rule Set

The Braces Rule Set has been added and serves the same purpose as the Braces Rule Set from Java:
It checks the use and placement of braces around if-statements, for-loops and so on.

IfStmtsMustUseBraces

Avoid using if statements without using braces to surround the code block. If the code
formatting or indentation is lost then it becomes difficult to separate the code being
controlled from the rest.

For instance, the following code shows the different. PMD would report on the not recommended approach:

if (foo)    // not recommended
    x++;

if (foo) {  // preferred approach
    x++;
}
WhileLoopsMustUseBraces

Avoid using 'while' statements without using braces to surround the code block. If the code
formatting or indentation is lost then it becomes difficult to separate the code being
controlled from the rest.

For instance, the following code shows the different. PMD would report on the not recommended approach:

while (true)    // not recommended
      x++;

while (true) {  // preferred approach
      x++;
}
IfElseStmtsMustUseBraces

Avoid using if..else statements without using surrounding braces. If the code formatting
or indentation is lost then it becomes difficult to separate the code being controlled
from the rest.

For instance, the following code shows the different. PMD would report on the not recommended approach:

// this is not recommended
if (foo)
       x = x+1;
   else
       x = x-1;

// preferred approach
if (foo) {
 ...
Read more

PMD 5.5.6 (19-April-2017)

20 Apr 19:00
Compare
Choose a tag to compare

19-April-2017 - 5.5.6

The PMD team is pleased to announce PMD 5.5.6.

This is a bug fixing release.

Fixed Issues

  • General
    • #324: [core] Automated release - github release notes missing
    • #337: [core] Version 5.5.4 seems to hold file lock on rules JAR (affects Windows only)