SonarQube Setup and GitHub Integration

SonarQube Setup and GitHub Integration

Why SonarQube?

In today’s competitive software development world, speed is crucial to develop new features, as well as improving existing features to stay ahead of the competition. Multiple developers of varying skill levels and work experience contribute to the software. Through the addition of new code lines the code base will grow larger over time. Through the differences level of experience and coding styles between the contributors the code base will also become more complex and in some areas even less efficient or insecure, making it more difficult to maintain.

SonarQube is a powerful static code analysis tool that helps development teams maintain high-quality, maintainable and secure code. It scans the the code base for potential issues like bugs, vulnerabilities and code smells to ensure problems are identified early. It can also be integrated into the CI/CD pipeline, ensuring that every code commit is automatically analyzed for issues. This integration provides developers with immediate feedback on code quality and security vulnerabilities. By using SonarQube, teams can siginificantly reduce the time spent on manual code reviews and prevent defects from reaching production, thereby improving overall efficiency and the software’s reliability.

Installation

SonarSource, the company behind SonarQube, provides a Docker Compose file that simplifies the process of running SonarQube. The code can be found at the following GitHub page. I’ve made slight adjustment to at the networks configuration settings and also moved credentials into environment variables stored in a .env file.

services:
  sonarqube:
    image: sonarqube:community
    restart: unless-stopped
    hostname: sonarqube
    container_name: sonarqube
    read_only: true
    depends_on:
      db:
        condition: service_healthy
    environment:
      SONAR_JDBC_URL: ${SONAR_JDBC_URL}
      SONAR_JDBC_USERNAME: ${SONAR_JDBC_USERNAME}
      SONAR_JDBC_PASSWORD: ${SONAR_JDBC_PASSWORD}
    volumes:
      - sonarqube_data:/opt/sonarqube/data
      - sonarqube_extensions:/opt/sonarqube/extensions
      - sonarqube_logs:/opt/sonarqube/logs
      - sonarqube_temp:/opt/sonarqube/temp
    ports:
      - "9000:9000"
    networks:
      - sast
  db:
    image: postgres:15
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -d ${POSTGRES_DB} -U ${POSTGRES_USER}"]
      interval: 10s
      timeout: 5s
      retries: 5
    hostname: postgresql
    container_name: postgresql
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    volumes:
      - postgresql:/var/lib/postgresql
      - postgresql_data:/var/lib/postgresql/data
    networks:
      - sast

volumes:
  sonarqube_data:
  sonarqube_temp:
  sonarqube_extensions:
  sonarqube_logs:
  postgresql:
  postgresql_data:

networks:
  sast:
    driver: bridge
SONAR_JDBC_URL: jdbc:postgresql://db:5432/${POSTGRES_DB}
SONAR_JDBC_USERNAME: <sonarqube_username>
SONAR_JDBC_PASSWORD: <sonarqube_password>
POSTGRES_USER: <postgres_username>
POSTGRES_PASSWORD: <postgres_password>
POSTGRES_DB: <postgres_database_name>

And finally run it with a simple

docker compose up #or docker-compose up

GitHub Integration

Now that Sonarqube is up and running, we can log in using our credentials and begin configuring it for integration with GitHub. The process is similar to integrating SonarQube with other DevOps platforms. Detailed instructions can be found in the documentation under the DevOps platform intergration section*.*

One thing I don’t like is that new projects are set to Public by default. To change this to Private, navigate to Administration → Projects → Management. On the page, just to the left of the blue Create Project button we will find the option to modify the default visibility setting for new projects, which can be switched from Public to Private.

Set up server base URL

First we need to configure a base URL for the application. To do this, we connect our application to a custom domain and secure it with a TLS certificate. For the sake of this example, I will use the domain example.com.

To set the base URL, navigate to Administration → General → Server base URL and enter the URL
(e.g., example.com).

Setting up a GitHub App

Now that we have configured the server base URL, we will create a GitHub Application to allow SonarQube access to the repositories. The steps presented are for a personal GitHub account, but they should also apply to GitHub organizations. For more information please refer to the documentation.

For this we log into out personal GitHub account and navigate to GitHub Profile → Settings → Developer Settings → New GitHub App. In the new Register new GitHub App page we will provide the following information:

  • GitHub App name → Provide a name for this application

  • Homepage URL → The base URL of SonarQube (example.com)

  • Callback URL → The base URL of SonarQube again

  • Webhook URL → Disable as per recommendation of the SonarQube documentation

  • Permissions

    • Repository permissions

      • Checks → Read & Write

      • Administration → Read-only

      • Metadata (GitHub.com) | Repository metadata (GitHub Enterprise) → Read-only

      • Pull Requests → Read & Write

      • Private repositories: Content → Read only

      • Code scanning alerts → Read & Write

    • Organizations permissions

      • Administration → Read-only

      • GitHub Copilot Business → Read-only

      • Members → Read-only

      • Projects → Read-only

    • Account permissions

      • Email addresses → Read-only
  • Select the “Only on this account” option under “Where can this GitHub App be installed?”

Once we are done creating the GitHub App, we will be taken to an overview page for newly created applications. Here we click the Generate a new client secret button, which generates a client secret that should be saved securely. It will be needed later to configure SonarQube. Also make notes of the App ID and Client ID of this application. Further down the page there is a Generate a private key button. We need to click it to generate and download the private key. Now that we have all the necessary credentials, we can continue the setup in SonarQube.

SonarQube DevOps Platform Integration

Now that we have created the GitHub application and saved all the necessary information, we can proceed in SonarQube. Navigate to Administration → Configuration → General Settings → DevOps Platform Integrations. Select GitHub and then click the Create Configuration button. This will open a popup window where we need to provide a name for the configuration. Next, we enter the GitHub API URL. Since we are using a personal GitHub account, we can use the default URL: api.github.com. In the following fields enter the App ID, Client ID and Client secret that we saved earlier. To provide the Private Key, simply retrieve it from the downloaded file.

cat <filename>.private-key.pem

-----BEGIN RSA PRIVATE KEY-----
AFGDSAFasdfasfasdfGAsd....
.........
SAFGSAgfaGADSFASDFSFSF
-----END RSA PRIVATE KEY-----

Copy the contents of the private key file and paste it directly into the provided field in the configuration. Once all required information has been entered, we submit the configuration and wait for the result. If everything is correct, we should see a confirmation message stating Configuration valid.

Next we navigate to the Projects page where we will se the Import from GitHub option. We select it and then choose our GitHub username from the dropdown list under Choose an organization. This will display all our repositories, from which we can select the ones we wish to import.

First Repository Scan

Let’s start our first repository scan. We navigate to Projects page → Import from GitHub → and select our username from dropdown. Then we choose a repository from the list of available repositories and click the Import button on the right.

On the next page, we select Use the global settings for now and create the project by clicking the Create Project button. Afterwards we will be directed to a new page where we can choose our analysis method. We select GitHub Actions.

On the following page, SonarQube will provide the necessary secrets, along with information for the sonar-project.properties and YAML files that need to be added to our repository. We follow the instructions, commit the required files to our project and shortly after, the pipeline should start running. Once the scan is complete, we will be able to view the results in our newly created project in SonarQube.