SonarQube: Static Code analysis

kaustubh shukla
4 min readFeb 3, 2021

Automated Code Quality analysis:

Static code analysis or Source code analysis is a method performed on ‘static’ (non-running) source code. With the help of static code analysis tools that attempt to automate the code audit process to highlight potential vulnerabilities. Static code analyzers check source code for specific vulnerabilities as well as for compliance with various coding standards.

Why use Static Analysis?

We have below points to advocate to use static code analysis tools during development process:

  • Get code internals before execution
  • Code quality maintenance can be automated.
  • Although not all but search for bugs can be automated at early stages.
  • Finding security problems can be automated at an early stages of the development.
  • Comparitive to Dynamic Application Security Testing (DAST) executes quickly.
  • We already use static code analysers if we use any IDE that already has static analyzers( for example Pycharm uses pep8, Rosyln for Visual Studio).

SonarQube:

SonarQube is the popular static analysis tool for continuously inspecting the code quality and security of your codebases and guiding development teams during code reviews. SonarQube is used for automated code review with CI/CD integration. It also offers quality-management tools to help us put it right actively.

Key features:

  • Multi-language
  • Security Analysis.
  • Release Quality code
  • Maintainability

Prerequisites:

The only prerequisite for running SonarQube is to have JDK 11 installed on your machine. For more information, please visit this link.

Installation:

To install the SonarQube, we have two options to install:

  1. Install as a single-node SonarQube instance.
  2. Install as a Server as a cluster

When we install SonarQube as a single-node instance, we have following three components:

1. The SonarQube server running the following processes:

  • a web server responsible for SonarQube user interface.
  • a search server based on ElasticSearch.
  • the compute engine which takes care of processing code analysis reports and saving them in the SonarQube database.

2. The database to store the following:

  • Metrics and issues for code quality and security generated during code scans.
  • The SonarQube instance configuration.

3. One or more scanners running on your build or CI servers to analyze projects.

Installing the database:

Several database engines are supported. Create an empty schema and a sonarqube user. Grant this sonaqube user permissions to create, update and delete objects for this schema.

Install SonarQube from the Zip file:

First, check the requirements. Then download and unzip the distribution and add the unzipped folder location to the PATH environment variable. Also, update wrapper.java.command in the wrapper.conf file in the conf folder to the JAVA path.

Setting the Access to the Database:

Edit sonar.properties file in the conf folder to configure the database settings. Templates are available for all the supported database.

Starting the web server:

To start the server, run the following script:

On Linux: bin/linux-x86–64/sonar.sh start

On macOS: bin/macosx-universal-64/sonar.sh start

On Windows: bin/windows-x86–64/Start.bat

We can now browse SonarQube interface at http://localhost:9000 . If you get an error related to port binding, please update default port in sonar.properties file in conf folder.

Default system adminstrator credentials are admin/admin which will be updated on first login to the system.

Analysing .net core project:

To add new .net core project to sonarqube, we have to follow below steps:

  • Click on ‘+’ sign on right side of the header which will open “Create a Project” interface in which we have to provide Project Key and display name.
  • In the next step, we have to generate a new token or use existing token.
  • Download the Sonar Scanner for MSBUILD and add the executable’s directory to the ‘%PATH%’ environment variable
  • In the final step, we have to run below commands in “command prompt for Visual Studio”.

SonnarScanner.MSBuild.exe begin /k:"<<ProjectKey>>" /d:sonar.host.url="<<URL>>" /d:sonar.login="<<token>>"

MSBuild

SonarScanner.MSBuild.exe end /d:sonar.login="<<token>>"

Or enter following commands if SonarScanner.MSBuild.Exe is not available

dotnet sonarscanner begin /k:"<<ProjectKey>>" /d:sonar.host.url="<<URL>>" /d:sonar.login="<<token>>"

MSBuild.exe

dotnet sonarscanner end /d:sonar.login="<<token>>"

Analysing Angular Application:

To analyse the Angular applicatio, we have to follow below steps:

There are specific scanners available for different build tools. For angular based application, we should use base sonar-scanner npm package.

npm i sonar-scanner --save-dev

After that, we have to add sonar-project.properties file to the root of the application. This defines the sonar instance and all the subsequent details. Cotent of the file will be similar to below:

sonar.host.url=http://localhost:9000

sonar.login=””

sonar.password=””

sonar.projectkey=

sonar.sourceEncoding=UTF-8

sonar.sources=src

sonar.test=src

sonar.exclusions=**/node_modules/**

sonar.test.inclusions=**/*.spec.ts

sonar.typescript.lcov.reportPaths=coverage/lcov.info

sonar.testExecutionReportPaths=reports/ut_report.xml

All the possible entries in the file can be found in this link

We need to add following npm library to add support for scanning the test execution report:

npm i karma-sonarqube-unit-reporter --save-dev

Update karma.conf.js to add this reporter

plugins:[

require(‘karma-sonarqube-unit-reporter’)

],

sonarQubeUnitReporter: {

sonarQubeVersion: ‘Latest’,

outputFile: ‘report/utreport.xml’,

overrideTestDescription: true,

testPaths: [‘./src’],

testFilePattern: ‘.spec.ts’,

userBrowserName: false,

},

reporters: [‘sonarqubeUnit’],

Add the final step in configuring the Angular project, we have to add sonar-scanner to the scripts in package.json

“scripts”: {

“sonar”: “sonar-scanner”

}

Once configured the project, As the sonar-scanner is dependent on the coverage and execution reports generated by third party karma plugins, lets create them by running following angular cli commant:

ng test — code-coverage — watch=false

Now run the scanner by executing following cli command:

npm run sonar

--

--