SonarQube 導入指引
導入效應
| 效應 | 說明 |
|---|---|
| Code Smell 偵測 | 自動抓出死程式碼、重複程式碼、過長方法、複雜度過高等問題 |
| Bug 預防 | 在 merge 前偵測空指標風險、資源外洩、邏輯錯誤 |
| 安全漏洞掃描 | 偵測 SQL Injection、XSS、硬編碼密碼等 OWASP Top 10 問題 |
| AI 產碼品質控管 | AI 快速產碼容易產生 Dead Code / Duplicate,SonarQube 即時攔截 |
| Quality Gate | 設定合併門檻:Coverage ≥ 80%、Bug = 0、Vulnerability = 0 |
| 歷史趨勢 | 追蹤 Code Quality 隨時間變化,量化改善成效 |
1. 安裝 SonarQube
1.1 Docker 快速啟動
docker run -d --name sonarqube \
-p 9000:9000 \
-e SONAR_ES_BOOTCHECK_DISABLE=true \
sonarqube:lts-community
1.2 預設帳號
URL: http://localhost:9000
Username: admin
Password: admin
1.3 安裝 Java Plugin(如需要)
在 SonarQube Marketplace 安裝: - SonarJava - SonarPHP - SonarPython
2. Maven 整合
2.1 安裝 Scanner
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>5.1.0.4627</version>
</plugin>
2.2 執行掃描
# 產生 Token(在 SonarQube UI: My Account > Security > Generate Token)
mvn sonar:sonar \
-Dsonar.host.url=http://localhost:9000 \
-Dsonar.token=<your-token>
3. Gradle 整合
plugins {
id 'org.sonarqube' version '6.0.1.5654'
}
sonar {
properties {
property "sonar.host.url", "http://localhost:9000"
property "sonar.token", project.findProperty("SONAR_TOKEN") ?: ""
}
}
./gradlew sonarqube
4. Quality Gate 設定
4.1 預設 Quality Gate 條件
| 指標 | 門檻 |
|---|---|
| New Bugs | 0 |
| New Vulnerabilities | 0 |
| New Security Hotspots | 0 |
| New Code Smells | ≤ 20 |
| New Coverage | ≥ 80% |
| New Duplicated Lines | ≤ 3% |
4.2 自訂 Quality Gate
# API 建立自訂 Quality Gate
curl -X POST "http://localhost:9000/api/qualitygates/create" \
-d "name=AI Guardrails Gate"
5. CI 整合
5.1 Azure Pipeline
- stage: CodeQuality
jobs:
- job: SonarQube
steps:
- task: Maven@4
inputs:
goals: 'verify'
- task: SonarQubePrepare@5
inputs:
SonarQube: 'SonarQube-Connection'
scannerMode: 'Maven'
projectKey: 'my-project'
- task: SonarQubeAnalyze@5
- task: SonarQubePublish@5
inputs:
pollingTimeoutSec: '300'
5.2 PR Check
SonarQube 可自動在 PR 上顯示 Quality Gate 結果:
# azure-pipelines.yml
- task: SonarQubePrepare@5
inputs:
extraProperties: |
sonar.pullrequest.key=$(System.PullRequest.PullRequestId)
sonar.pullrequest.branch=$(System.PullRequest.SourceBranch)
sonar.pullrequest.base=$(System.PullRequest.TargetBranch)
6. AI 產碼常見問題
| AI 產碼問題 | SonarQube 偵測 |
|---|---|
| 未使用的 import | Code Smell |
| 重複程式碼區塊 | Duplicated Lines |
| 空的 catch 區塊 | Bug |
| 硬編碼 IP/密碼 | Security Hotspot |
| 過長方法 (> 100 行) | Code Smell |
| 複雜度過高 (> 15) | Code Smell |
7. Secret Detection
SonarQube Enterprise 版本支援 Secret Detection:
# sonar-project.properties
sonar.secret扫描.enabled=true
可偵測: - AWS Access Key - Azure Storage Key - Database Password - Private Keys
8. 參考資源
- 官方文件:https://docs.sonarqube.org/
- SonarJava Rules:https://rules.sonarsource.com/java/
- Quality Gate API:https://docs.sonarqube.org/latest/extension/endpoints/api/