Apex PMD: Problem: Validate CRUD permission before SOQL/DML operation
PMD's Apex ruleset is checking to see that you are enforcing/respecting security in your code.
ISV's Managed packages released to the AppExchange must do this as mandatory criteria in the security review process. The spirit of the requirement is to honor the access control configuration choices that org admins make within ISV application offerings. If an admin explicitly restricts access control for sharing/CRUD/FLS then ISV offerings should respect that.
Theoretically, you should be able to remove this rule from the VS Code PMD ruleset (or build a custom ruleset xml which doesn't include it), if you don't want to be warned about a concern that may not apply to your application's situation.
Looks like the VS Code PMD plugin allows for a custom ruleset. You could take this one here and customize it, removing the rules which are not important to you such as this one:
<rule ref="category/apex/security.xml/ApexCRUDViolation"
message="Validate CRUD permission before SOQL/DML operation">
Related:
GitHub: PMD: Apex Rule Set
Enforcing Object and Field Permissions
Authorization and Access Control
Trailhead: Prevent CRUD and FLS Violations
removing that kind of rule is not the solution, find an appropriate solution for it, and make changes in your code. I think the below changes in your code might help.
SObject.sObjectType.getDescribe().isAccessible()
SObject.sObjectType.getDescribe().isCreateable()
SObject.sObjectType.getDescribe().isUpdateable()
SObject.sObjectType.getDescribe().isDeleteable()
SObject is Object which we want to try over
PMD will not throw error if you follow the below syntax:-
List<Contact> contacts = new List<Contact>();
// You add some code to populate the contacts name and phone. Before performing dml you're checking the object and field level permissions like:-
if(Contact.SObjectType.getDescribe().isAccessible() && Schema.SObjectType.Contact.fields.Name.isAccessible() && Schema.SObjectType.Contact.fields.Phone.isAccessible()) {
insert contacts;
}
However, the good news is you don't have to check for permissions in the Spring 20 release. You can handle it in the query itself like:-
Contact c = [SELECT Email FROM Contact WHERE Id=:Id WITH SECURITY_ENFORCED];
And before performing a DML, you can strip the fields the user doesn't have access to like:-
SObjectAccessDecision decision = Security.stripInaccessible(AccessType.CREATABLE, contacts);
insert contacts;
Have a look at this link for more info:- Validate CRUD permission before SOQL/DML operation ? Well...that's History