sonar-dotnet icon indicating copy to clipboard operation
sonar-dotnet copied to clipboard

New Rule Idea: Metadata validation

Open zsolt-kolbay-sonarsource opened this issue 1 year ago • 0 comments

TITLE Attributes should be used properly

WHY IS THIS AN ISSUE Attributes in .NET provide a way of ensuring that data adheres to certain conditions or constraints. Misusing these attributes can cause unexpected program behavior, vulnerabilities, or data integrity issues.

Possible misuses include:

  • An attribute that isn't compatible with the property/field/etc. type.
  • The attribute references a non-existing member.
  • A type/member is decorated with multiple attributes that aren't compatible with each other.
  • The attribute parameters aren't correct.
  • the same attribute is used twice (redundantly) on the same type/member (with the same parameters)

None of these are currently validated during the build. The only rule that's always enforced by the compiler is whether the attribute is used on the right kind of syntax node (e.g., if the attribute can only be used on an enum declaration, then trying to annotate a method parameter with it will cause the build to fail).

NONCOMPLIANT CODE EXAMPLE

public class User
{
    [StringLength(10)] // Noncompliant; not suitable for an int property
    public int UserId { get; set; }

    [Compare("ConfirmedPassword")] // Noncompliant; there's no 'ConfirmedPassword' property in the class
    public string Password { get; set; }

    [Required]
    [ValidateNever] // Noncompliant; contradictory validation attributes
    public string Email { get; set; }

    [Range(100, 1)] // Noncompliant; start of the range is higher than the end
    public int Age { get; set; }
}

COMPLIANT CODE EXAMPLE

public class User
{
    public int UserId { get; set; }

    [Compare("ConfirmedPassword")]
    public string Password { get; set; }

    public string ConfirmedPassword { get; set; }

    [Required]
    public string Email { get; set; }

    [Range(1, 100)]
    public int Age { get; set; }
}

BENEFITS

IMPLEMENTATION We will first need a specification sprint. Go through the attributes available in .NET. Attributes from:

  • Base Class Library
  • popular Microsoft frameworks: ASP.NET MVC, Blazor, WPF, Entity Framework, etc.
  • popular 3rd party libraries: JSON.NET, Automapper, etc. Make a list of attributes and how they can be misused, and then try to find patterns in the list (see a non-complete list under WHY IS THIS AN ISSUE). Then figure out a way to cover as many of these issues as possible.

RESOURCES

  • https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/
  • https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation