GenAIHub
Back to Technical
Code Quality

SonarQube

Continuous code quality and security analysis. Detect bugs, vulnerabilities, and code smells across 30+ programming languages with automated static analysis.

πŸ” What is SonarQube?

SonarQube is an open-source platform for continuous inspection of code quality. It performs automatic reviews with static analysis to detect bugs, code smells, and security vulnerabilities on 30+ programming languages. It integrates seamlessly with CI/CD pipelines to enforce quality gates before code reaches production.

πŸ›

Bug Detection

Find issues early

πŸ”’

Security

Vulnerability scanning

🧹

Code Smells

Maintainability

πŸ“Š

Coverage

Test tracking

πŸ’‘ Key Insight: SonarQube follows a "Clean as You Code" methodology β€” focus on keeping new code clean rather than fixing legacy issues all at once.

πŸ“š Core Concepts

πŸ› Bugs

Code that is demonstrably wrong or will cause unexpected runtime behavior. Examples: null pointer dereference, infinite loops, resource leaks.

πŸ”“ Vulnerabilities

Security weaknesses that could be exploited by attackers. Examples: SQL injection, XSS, hardcoded credentials, insecure deserialization.

🧹 Code Smells

Maintainability issues that make code harder to understand or modify. Examples: duplicated code, overly complex functions, unused variables.

πŸ›‘οΈ Security Hotspots

Code that requires manual review to determine if it's potentially vulnerable. Examples: cryptographic usage, authentication patterns, permission checks.

🚦 Quality Gate

A Quality Gate is a set of conditions that determine whether your code is ready for production. If any condition fails, the gate fails and the pipeline should be blocked.

Metric Condition Default Threshold
New Bugs Must be 0
New Vulnerabilities Must be 0
New Code Smells Severity A rating
Code Coverage New code β‰₯ 80%
Duplications New code ≀ 3%
Security Hotspots Reviewed 100%

βœ… Gate Passed

All conditions met. Pipeline continues to deployment. New code meets quality standards.

❌ Gate Failed

One or more conditions not met. Pipeline blocked. Developer must fix issues before merging.

🌐 Supported Languages

Python
Java
TypeScript
C#
JavaScript
Go
C/C++
Kotlin
PHP
Ruby
Scala
Swift

βš™οΈ CI/CD Integration

GitHub Actions

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

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  sonarqube:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Full history for accurate blame

      - name: SonarQube Scan
        uses: SonarSource/sonarqube-scan-action@v3
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}

      - name: Quality Gate Check
        uses: SonarSource/sonarqube-quality-gate-action@v1
        timeout-minutes: 5
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}

πŸ“„ sonar-project.properties

# Project Configuration
sonar.projectKey=my-genai-project
sonar.projectName=GenAI Application
sonar.projectVersion=1.0

# Source directories
sonar.sources=src
sonar.tests=tests

# Language-specific settings
sonar.python.version=3.11
sonar.python.coverage.reportPaths=coverage.xml

# Exclusions
sonar.exclusions=**/node_modules/**,**/venv/**,**/__pycache__/**
sonar.test.exclusions=**/tests/**

# Encoding
sonar.sourceEncoding=UTF-8

🐳 Run SonarQube Locally with Docker

# Start SonarQube server
docker run -d --name sonarqube \
  -p 9000:9000 \
  -v sonar_data:/opt/sonarqube/data \
  -v sonar_logs:/opt/sonarqube/logs \
  sonarqube:community

# Access at http://localhost:9000
# Default credentials: admin / admin

# Run scanner on your project
docker run --rm \
  -e SONAR_HOST_URL="http://host.docker.internal:9000" \
  -e SONAR_TOKEN="your-token-here" \
  -v "$(pwd):/usr/src" \
  sonarsource/sonar-scanner-cli

πŸ€– SonarQube for GenAI/ML Projects

AI/ML projects benefit greatly from static analysis. Common issues SonarQube catches in GenAI codebases:

❌ Common Issues Found

  • β€’ Hardcoded API keys (OpenAI, Azure, AWS)
  • β€’ Unhandled exceptions in API calls
  • β€’ Resource leaks (file handles, DB connections)
  • β€’ Insecure HTTP calls to model endpoints
  • β€’ Missing input validation on user prompts

βœ… Best Practices Enforced

  • β€’ Environment variables for secrets
  • β€’ Proper error handling and retries
  • β€’ Context managers for resources
  • β€’ HTTPS for all external API calls
  • β€’ Input sanitization and validation

⚠️ Warning: SonarQube detects hardcoded secrets with high accuracy. Always use environment variables or a secrets manager (Vault, AWS Secrets Manager, GCP Secret Manager) for API keys in GenAI applications.

πŸ“‹ Editions Comparison

Feature Community (Free) Developer Enterprise
Languages 15+ 25+ 30+
Branch Analysis ❌ βœ… βœ…
PR Decoration ❌ βœ… βœ…
SAST / Taint Analysis Basic βœ… βœ…
Portfolio Management ❌ ❌ βœ…
Pricing Free From $150/yr From $20K/yr

πŸ“ˆ Key Metrics & Ratings

Reliability Rating

  • A β€” 0 bugs
  • B β€” 1 minor bug
  • C β€” 1 major bug
  • D β€” 1 critical bug
  • E β€” 1 blocker bug

Security Rating

  • A β€” 0 vulnerabilities
  • B β€” 1 minor vuln
  • C β€” 1 major vuln
  • D β€” 1 critical vuln
  • E β€” 1 blocker vuln

Maintainability Rating

  • A β€” Technical debt ratio ≀ 5%
  • B β€” 6-10%
  • C β€” 11-20%
  • D β€” 21-50%
  • E β€” > 50%

βœ… Best Practices

Do's

  • Enforce Quality Gates in CI/CD pipeline
  • Focus on "Clean as You Code" (new code first)
  • Review Security Hotspots regularly
  • Set up PR decoration for developer feedback
  • Track code coverage trends over time

Don'ts

  • Ignore Quality Gate failures
  • Suppress warnings without understanding them
  • Skip security reviews for "internal" projects
  • Set coverage thresholds too low (< 60%)
  • Exclude entire directories to pass the gate

βš–οΈ SonarQube vs Alternatives

Tool Type Self-Hosted Best For
SonarQube SAST + Quality βœ… Full code quality + security
SonarCloud SaaS ❌ Cloud-native teams
CodeClimate Quality ❌ Maintainability focus
Snyk Security ❌ Dependency vulnerability scanning
ESLint / Pylint Linting βœ… Language-specific linting

πŸ“– Learn More

Related Topics

Test Your Knowledge

Score 8/10 or higher to pass