๐Ÿ”’ Security

SonarQube

SonarQube

A code quality and security analysis platform. Static analysis, technical debt management.

๐Ÿ“– Detailed Explanation

SonarQube is an open-source static analysis platform that automatically analyzes the quality and security of source code. Developed by SonarSource, it supports more than 30 programming languages, including Java, JavaScript, TypeScript, Python, C/C++, C#, Go, and PHP. It detects code smells, bugs, and security vulnerabilities (OWASP Top 10, CWE), and estimates technical debt in units of time.

The core concept of SonarQube is the Quality Gate. You set thresholds for quality metrics such as code coverage, duplication rate, and the number of bugs/vulnerabilities in new code, and integrate it with the CI/CD pipeline so that deployment is possible only when these thresholds are met. In line with the "Clean as You Code" philosophy, it applies strict standards to newly written/modified code to gradually improve the quality of the codebase.

Analysis results can be viewed in a web dashboard by project and by issue. For each issue, it suggests a problem description, its impact, and how to fix it, and through the IDE plugin (SonarLint), developers can receive real-time feedback while coding. With the Pull Request analysis feature, it automatically detects problems before code review and leaves a report as a PR comment.

SonarQube is offered in Community (free), Developer, Enterprise, and Data Center editions. Higher editions provide additional features such as OWASP/CWE mapping, branch analysis, PR decoration, and support for more languages. SonarCloud is the SaaS version and integrates easily with GitHub, GitLab, and Azure DevOps. It is widely used as a SAST (Static Application Security Testing) tool in DevSecOps pipelines.

๐Ÿ’ป Code Example

Running SonarQube with Docker

# SonarQube ์„œ๋ฒ„ ์‹คํ–‰
docker run -d --name sonarqube \
  -p 9000:9000 \
  -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true \
  -v sonarqube_data:/opt/sonarqube/data \
  -v sonarqube_extensions:/opt/sonarqube/extensions \
  -v sonarqube_logs:/opt/sonarqube/logs \
  sonarqube:lts-community

# ๋ธŒ๋ผ์šฐ์ €์—์„œ http://localhost:9000 ์ ‘์†
# ์ดˆ๊ธฐ ๊ณ„์ •: admin / admin

# PostgreSQL๊ณผ ํ•จ๊ป˜ ์‹คํ–‰ (ํ”„๋กœ๋•์…˜)
# docker-compose.yml
# version: "3"
# services:
#   sonarqube:
#     image: sonarqube:lts-community
#     depends_on:
#       - db
#     environment:
#       SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonar
#       SONAR_JDBC_USERNAME: sonar
#       SONAR_JDBC_PASSWORD: sonar
#     ports:
#       - "9000:9000"
#   db:
#     image: postgres:15
#     environment:
#       POSTGRES_USER: sonar
#       POSTGRES_PASSWORD: sonar
#       POSTGRES_DB: sonar

sonar-project.properties Configuration

# ํ”„๋กœ์ ํŠธ ์‹๋ณ„
sonar.projectKey=my-project
sonar.projectName=My Project
sonar.projectVersion=1.0

# ์†Œ์Šค ์ฝ”๋“œ ์œ„์น˜
sonar.sources=src
sonar.tests=tests
sonar.exclusions=**/node_modules/**,**/dist/**,**/*.test.ts

# ์–ธ์–ด๋ณ„ ์„ค์ •
sonar.language=java
sonar.java.binaries=target/classes
sonar.java.source=17

# ์ปค๋ฒ„๋ฆฌ์ง€ ๋ฆฌํฌํŠธ ์—ฐ๋™
sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.python.coverage.reportPaths=coverage.xml

# ์ •์  ๋ถ„์„ ๋ฆฌํฌํŠธ ์—ฐ๋™ (ESLint, Pylint ๋“ฑ)
sonar.eslint.reportPaths=eslint-report.json
sonar.python.pylint.reportPaths=pylint-report.txt

# ์ธ์ฝ”๋”ฉ
sonar.sourceEncoding=UTF-8

# ๋ธŒ๋žœ์น˜ ๋ถ„์„ (Developer Edition ์ด์ƒ)
# sonar.branch.name=feature/my-feature

# Pull Request ๋ถ„์„
# sonar.pullrequest.key=123
# sonar.pullrequest.branch=feature/my-feature
# sonar.pullrequest.base=main

GitHub Actions CI/CD Integration

# .github/workflows/sonarqube.yml
name: SonarQube Analysis

on:
  push:
    branches: [main, develop]
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  sonarqube:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # ์ „์ฒด ํžˆ์Šคํ† ๋ฆฌ (blame ๋ถ„์„์šฉ)

      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          java-version: '17'
          distribution: 'temurin'

      - name: Cache SonarQube packages
        uses: actions/cache@v4
        with:
          path: ~/.sonar/cache
          key: ${{ runner.os }}-sonar

      - name: Build and Test with Coverage
        run: |
          ./gradlew build jacocoTestReport

      - name: SonarQube Scan
        uses: SonarSource/sonarqube-scan-action@master
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
        with:
          args: >
            -Dsonar.projectKey=my-project
            -Dsonar.sources=src/main
            -Dsonar.tests=src/test
            -Dsonar.java.binaries=build/classes
            -Dsonar.coverage.jacoco.xmlReportPaths=build/reports/jacoco/test/jacocoTestReport.xml

      # PR ๋ถ„์„ ์‹œ Quality Gate ๊ฒฐ๊ณผ ํ™•์ธ
      - name: SonarQube Quality Gate
        uses: SonarSource/sonarqube-quality-gate-action@master
        timeout-minutes: 5
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}

Python Project Analysis Example

# ์˜์กด์„ฑ ์„ค์น˜
pip install coverage pytest pytest-cov

# ํ…Œ์ŠคํŠธ ๋ฐ ์ปค๋ฒ„๋ฆฌ์ง€ ์ˆ˜์ง‘
pytest --cov=src --cov-report=xml --cov-report=html tests/

# SonarScanner ์‹คํ–‰
sonar-scanner \
  -Dsonar.projectKey=my-python-project \
  -Dsonar.sources=src \
  -Dsonar.tests=tests \
  -Dsonar.python.coverage.reportPaths=coverage.xml \
  -Dsonar.python.version=3.11 \
  -Dsonar.host.url=http://localhost:9000 \
  -Dsonar.token=$SONAR_TOKEN

Using the SonarQube API

import requests
from typing import Optional

class SonarQubeClient:
    """SonarQube REST API ํด๋ผ์ด์–ธํŠธ"""

    def __init__(self, base_url: str, token: str):
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        self.session.auth = (token, '')  # token as username, empty password

    def get_project_status(self, project_key: str) -> dict:
        """ํ”„๋กœ์ ํŠธ Quality Gate ์ƒํƒœ ์กฐํšŒ"""
        response = self.session.get(
            f"{self.base_url}/api/qualitygates/project_status",
            params={"projectKey": project_key}
        )
        response.raise_for_status()
        return response.json()

    def get_issues(
        self,
        project_key: str,
        severities: Optional[list] = None,
        types: Optional[list] = None,
        page_size: int = 100
    ) -> list:
        """ํ”„๋กœ์ ํŠธ ์ด์Šˆ ๋ชฉ๋ก ์กฐํšŒ"""
        params = {
            "componentKeys": project_key,
            "ps": page_size,
            "resolved": "false"
        }
        if severities:
            params["severities"] = ",".join(severities)
        if types:
            params["types"] = ",".join(types)

        all_issues = []
        page = 1

        while True:
            params["p"] = page
            response = self.session.get(
                f"{self.base_url}/api/issues/search",
                params=params
            )
            response.raise_for_status()
            data = response.json()

            all_issues.extend(data["issues"])

            if len(all_issues) >= data["total"]:
                break
            page += 1

        return all_issues

    def get_metrics(self, project_key: str, metrics: list) -> dict:
        """ํ”„๋กœ์ ํŠธ ๋ฉ”ํŠธ๋ฆญ ์กฐํšŒ"""
        response = self.session.get(
            f"{self.base_url}/api/measures/component",
            params={
                "component": project_key,
                "metricKeys": ",".join(metrics)
            }
        )
        response.raise_for_status()
        return response.json()

    def create_quality_gate_condition(
        self,
        gate_name: str,
        metric: str,
        operator: str,  # "LT", "GT"
        error: str
    ):
        """Quality Gate ์กฐ๊ฑด ์ถ”๊ฐ€"""
        # ๋จผ์ € gate ID ์กฐํšŒ
        gates = self.session.get(
            f"{self.base_url}/api/qualitygates/list"
        ).json()

        gate_id = None
        for gate in gates["qualitygates"]:
            if gate["name"] == gate_name:
                gate_id = gate["id"]
                break

        if not gate_id:
            raise ValueError(f"Quality Gate '{gate_name}' not found")

        response = self.session.post(
            f"{self.base_url}/api/qualitygates/create_condition",
            data={
                "gateId": gate_id,
                "metric": metric,
                "op": operator,
                "error": error
            }
        )
        response.raise_for_status()
        return response.json()

# ์‚ฌ์šฉ ์˜ˆ์ œ
client = SonarQubeClient("http://localhost:9000", "squ_xxxxx")

# Quality Gate ์ƒํƒœ ํ™•์ธ
status = client.get_project_status("my-project")
print(f"Quality Gate: {status['projectStatus']['status']}")

# ์‹ฌ๊ฐํ•œ ์ด์Šˆ ์กฐํšŒ
critical_issues = client.get_issues(
    "my-project",
    severities=["BLOCKER", "CRITICAL"],
    types=["BUG", "VULNERABILITY"]
)
print(f"Critical issues: {len(critical_issues)}")

# ์ฃผ์š” ๋ฉ”ํŠธ๋ฆญ ์กฐํšŒ
metrics = client.get_metrics("my-project", [
    "coverage",
    "duplicated_lines_density",
    "sqale_rating",  # Maintainability
    "reliability_rating",
    "security_rating",
    "ncloc"  # Lines of code
])
for measure in metrics["component"]["measures"]:
    print(f"{measure['metric']}: {measure['value']}")

๐Ÿ—ฃ๏ธ How It's Said in Practice

  • "This PR failed the Quality Gate. New code coverage is below 80%, so we need to add tests."
  • "SonarQube detected 3 Critical security vulnerabilities. This code could be vulnerable to SQL Injection, so it needs to be fixed."
  • "Technical debt has been measured at 20 days. Let's plan a refactoring sprint and reduce it gradually."
  • "If you install the SonarLint IDE plugin, you can check issues locally in advance before committing."
  • "What is the difference between static analysis and dynamic analysis? When should each be used?"
  • "What is a Quality Gate, and how is it used in a CI/CD pipeline?"
  • "Give an example of a code smell and explain why it can be a problem."
  • "What types of security vulnerabilities does SonarQube detect?"

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

  • "SonarQube flagged this function as having high Cognitive Complexity. It would be good to split it into smaller functions."
  • "This SQL query inserts parameters through string concatenation, so a SQL Injection warning is showing up. Use PreparedStatement."
  • "A duplicate code block was detected. Extracting it into a common function will make maintenance easier."

โš ๏ธ Cautions

False Positive Management

Some of the issues detected by SonarQube may not be actual problems (False Positives). Mark them as Won't Fix or False Positive to reduce noise, and create a custom rule profile to tailor it to your team.

Incremental Improvement Strategy

Introducing SonarQube to a legacy codebase can surface thousands of issues. Do not try to resolve all issues at once; instead, follow the "Clean as You Code" principle and improve gradually by applying strict standards only to new code.

Don't Blindly Trust Coverage

80% code coverage does not guarantee quality. What matters more is whether the tests are meaningful and whether they cover edge cases. Tests that merely execute code just to raise coverage have no value.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More