SSW Foursquare

Rules to Better Code Quality - 5 Rules

  1. Do you run the Code Health checks in your VisualStudio.com Continuous Integration Build?

    The real value of the code health system is that is made improvements in code quality more visible to the team and managers. By including several steps to the build process, the results of the analysers included in previous steps can be extracted out and summarised in a report spanning the project's lifetime.

    What Steps to Include in the Build Definition

    Summary:

    1. Ensure "Restore NuGet Packages" & "Build Solution" are in the build definition to run the Roslyn analysers.
    2. Add several npm and command line steps to the build definition to run tslint. (On premises builds require an additional step).
    3. Include an identifying variable "PrimaryBuild" to the build definition.
    4. Check the build is running without issues.

    The resulting build should look like this:

    VSO Build Good 1
    Figure: Good example - Build Passing with no summary issues

    Ensure utilisation of TeamBuild2015 or higher. (No support for XAML builds) Edit the build definition on <CompanyName>.visualstudio.com, and add the following build tasks. If your project does not contain TypeScript files, then you do not need to include the TSLint build tasks.

    VSO BuildDefinition V3
    Figure: Good example - Steps added to build definition

    VSO DirectoryExampleV2
    Figure: Example directory for TSLint run commands

    Under advanced for the Command Line tasks, the Working Directory can be specified if necessary.

    TsLint
     **Npm** - Install tslint and typescript  
     **Name:** npm install tslint  
     **Working Folder:** &lt;Top Directory&gt;  
     **Npm Command:** install  
     **Arguments:** -g tslint typescript  
      
     **Command Line** - Check the version (Useful to determine rule discrepancies across builds)  
     **Name:** Check tslint version   
     **Tool:** tslint   
     **Arguments:** -v  
    
     **Command Line** - Builds a default configuration file for the build (Without it issues can differ between build and development environment  
     **Name:** Create tslint config file  
     **Tool:** tslint  
     **Arguments:** --init  
    
     **Command Line** - Run tslint, force is required to stop the build from crashing (TSLint will return and exit code of 1 regardless of if issues exist)  
     **Name:** Run tslint  
     **Tool:** TSLint  
     **Arguments:** --force &lt;Solution Directory&gt;/\*\*/\*.ts{,x}  

    If your build is being hosted, then the config file must be reloaded every time. If your build is running on premises, the config file will attempt to load over the existing one and break the build.

    If this is the case, just add a step to delete your config file after the scan is complete.

    VSO RemoveConfig
    Figure: Command line step to remove the config file (tslint.json) after the linter has run

     **Command Line** - Remove the tslint config file, as it will break future scan if the build is on premises if a config file already exists and an attempt to add another one is made.  
     **Name:** Remove tslint config  
     **Tool:** del  
     **Arguments:** tslint.json  

    Once complete, save the build definition and run the build.

    Then check the build is successful.

    If the build fails (due to errors), these should be corrected in the development environment.

    Include "PrimaryBuild" variable

    For the purposes of reporting, a unique tag must be added to the build definition which the Code Health steps have been applied to.This is done with the addition of a variable (Name = PrimaryBuild, Value = true)

    VSO AddVariableTag
    Figure: Steps to add PrimaryBuild variable to build definition

    Check the build is running without issues

    VSO Build Bad 1
    Figure: Bad Code with a Good Code Health Implementation - Build broke due to compile errors. Must fix to proceed

    VSO Build Ok 1
    Figure: Bad Code with a Good Code Health Implementation - Successful build with warnings. These should be reprioritised as errors, or removed

    VSO Build Good 1
    Figure: Good Code with a Good Code Health Implementation - Successful build with no warnings

  2. Do you use the Code Health Extensions in VS Code?

    For lightweight web projects such as Angular, often VS Code is more appropriate than Visual Studio. So make sure your code quality remains consistent with CSSLint and ESLint.

    Which Extensions to Use in VS Code

    For web projects, we advocate the use of CSSLint for css files and ESLint for typescript files. (Why you should be using TypeScript instead of JavaScript) Linters for these can be easily added to VS Code via extensions. Simply select the "Extensions" tab, search for "CSSLint" and "ESLint" and click "Install" on each respectively.

    vs code extensions
    Figure: Addition of CSSLint and ESLint to VS Code Project

    If you prefer not to use the Extensions, you can install them using npm as normal.CSSLint (CSSLint npm guide) ESLint (ESLint npm guide)

  3. Do you use the Code Health Extensions in Visual Studio?

    The code quality standard should extend the Visual Studio Analyzer. A wide variety of additional analyzers can be included via Nuget, the minimum standard should include Roslyn Security Guard.

    Which Packages to Install in Visual Studio

    Search & Install the NuGet packages:

    VS InstallNuGetPackages
    Figure: Steps to install NuGet Packages

    Issues from these will now be returned in the Visual Studio analyzer error list.

    VS RoslynRules
    Figure: New Roslyn Rule issues raised in Visual Studio Analyzer

    Your goal should be to get the issues in a solution down to zero.

    If you believe the issues being raised are not important, please check the section below which outlines how to change the ruleset.

    Modify Visual Studio Analysis Ruleset

    The goal is to develop a shared ruleset across projects. This will ensure the same standard and quality of code is maintained across all of the company's projects.

    Any project specific rules should be documented in "_docs\Instructions-CodeHealth.md" which is to be kept in the solution as per Do you make awesome documentation?

    You can configure the severity of analyzer rules in an EditorConfig file.

    Follow the rule Do you keep your code consistent using .editorconfig? to add EditorConfig file to your project or solution.

  4. Do you keep your code consistent using .editorconfig?

    It's important that the code in a project is kept consistent. This is hard to do when you have developers working in different environments.

    Using a .editorconfig file is the best way to manage this.

    See the EditorConfig file specification

    Most IDEs will automatically find and use a .editorconfig file to format code.

    See Keep your code clean, automatically!.

    vs2022 add editorconfig
    Good example - Project using a ".editorconfig" file

    vs 2022 stylecop
    Bad example - Project using StyleCop (old)

    Creating .editorconfig files

    In VS 2022

    1. Open the Add New Item dialog (Ctrl+Shift+A)
    2. Search for "EditorConfig"
    3. Select a config file depending on your project

    vs2022 add editorconfig
    Figure: Creating .editorconfig in VS 2022

    Manually

    1. Create a new file called .editorconfig at the root of your project
    2. Add styling rules based on your needs

    Ensuring compliance

    To ensure your team is following this standard, you can add it to your Definition of Done.

    Additionally, you can have a PR check that enforces .editorconfig rules, but its always better to do this locally.

    Learn more on:

  5. Do you stay safe against the OWASP Top 10?

    The Open Web Application Security Project (OWASP) is a non-profit charity organization whose sole purpose is to enable other organizations to develop applications that can be trusted.  Their most prominent piece of literature is the OWASP Top 10 – a list of the most critical risks found in software.  It is a “living” list, which means it is updated as vulnerabilities become known and more or less common.

    OWASP Top 10 2021

    The current OWASP Top 10 states the following are the top risks for web applications today. Knowing and securing against these will give the biggest bang-for-buck in securing your website.

    • Broken Access Control: Insufficient controls in place to implement the principle of least privilege, insufficient access control protections
    • Cryptographic Failures: Data transmitted in clear text, sensitive data not encrypted at rest, using weak or broken cryptography algorithms
    • Injection: Failure to validate user-supplied data, queries not parameterized
    • Insecure Design: Security not considered as a baseline principle, security added as an after-thought (essentially, need to "shift-left" security)
    • Security Misconfiguration: Insecure default configurations, misconfigured HTTP headers and verbose error messages containing sensitive information
    • Vulnerable and Outdated Components: Packages and dependencies not kept up to date, versions with known vulnerabilities kept in the product
    • Identification and Authentication Failures: Brute force attacks, credential stuffing, missing MFA, permits weak passwords, simple password recovery
    • Software and Data Integrity Failures:  Failure of infrastructure configuration to protect against exploits, e.g. supply chain attacks, dependency package spoofing
    • Security Logging and Monitoring Failures: Not logging security events, not monitoring or auditing logs, not raising alerts for suspicious events
    • Server-Side Request Forgery: Arbitrarily fetching data from user supplied URLs

    Other Resources

    Protecting against these is a large topic in their own right. There are plenty of resources with information on protecting against these, linked below:

    • Troy Hunt – Protecting your web apps from the tyranny of evil with OWASP - This video goes through the OWASP Top 10 in more detail, describing each risk, how to exploit it, and how to protect against it
    • OWASP Top 10 - The OWASP home page is a little difficult to navigate but contains fantastic information on the risks and how to protect against them. Use the link above to get details on each of the vulnerabilities, with examples on attacking, “Cheat Sheets” for prevention and risk/impact assessment
We open source. Powered by GitHub