Semgrep 導入指引

導入效應

效應 說明
自訂規則引擎 用簡單語法寫出团队專屬的 lint 規則,例如禁止 RestTemplate、強制 WebClient
AI 產碼守門 AI 產碼後直接掃描,確保符合團隊 Coding Standard
多語言支援 Java / Python / TypeScript / Go / JavaScript 全支援
社群規則 上千條 pre-built 規則(OWASP、CWE、最佳實踐)可直接使用
快速掃描 比 SonarQube 快 10-100x,適合 PR 即時檢查
零設定 CI semgrep ci 一行指令搞定

1. 安裝 Semgrep

# macOS / Linux
brew install semgrep

# pip
pip install semgrep

# Docker
docker pull semgrep/semgrep

2. 基本使用

# 掃描專案(使用預設規則)
semgrep scan

# 使用 Java 規則
semgrep scan --config auto

# 掃描特定目錄
semgrep scan src/

# 只顯示 Error 級別
semgrep scan --config auto --error

3. 自訂規則

3.1 禁止 RestTemplate,強制使用 WebClient

# rules/no-rest-template.yaml
rules:
  - id: no-rest-template
    pattern: RestTemplate
    message: "禁止使用 RestTemplate,請使用 WebClient (Reactive)"
    languages: [java]
    severity: ERROR
    metadata:
      category: best-practice
      technology: [spring]

3.2 禁止 System.out

rules:
  - id: no-system-out
    pattern: System.out.println(...)
    message: "禁止使用 System.out.println,請使用 Logger"
    languages: [java]
    severity: WARNING
    fix: "logger.info($1)"

3.3 強制使用 Optional

rules:
  - id: use-optional
    pattern: |
      if ($X != null) {
          ...
      }
    message: "考慮使用 Optional 替代 null 檢查"
    languages: [java]
    severity: WARNING

3.4 禁止 Hardcoded Password

rules:
  - id: no-hardcoded-password
    patterns:
      - pattern: |
          String $PASS = "...";
      - metavariable-regex:
          metavariable: $PASS
          regex: (?i)(password|secret|token|key)
    message: "禁止硬編碼密碼/金鑰"
    languages: [java]
    severity: ERROR

3.5 自訂規則集

# rules/team-rules.yaml
rules:
  - id: enforce-logger
    pattern: LoggerFactory.getLogger($CLASS.class)
    message: "使用 SLF4J Logger"
    languages: [java]
    severity: WARNING

  - id: no-optional-get
    pattern: |
      $OPT.get()
    message: "避免 Optional.get(),使用 orElse/orElseThrow"
    languages: [java]
    severity: ERROR

  - id: enforce-immutable
    pattern: |
      public class $CLASS { ... }
    message: "考慮將資料類別設為 record  final"
    languages: [java]
    severity: WARNING

4. CI 整合

4.1 Azure Pipeline

- stage: CodeAnalysis
  jobs:
    - job: Semgrep
      steps:
        - script: |
            pip install semgrep
            semgrep scan --config auto --error --json --output semgrep-results.json
          displayName: 'Semgrep Scan'
        - task: PublishBuildArtifacts@1
          inputs:
            pathToPublish: 'semgrep-results.json'
            artifactName: 'semgrep-report'
          condition: always()

4.2 GitHub Actions

- name: Semgrep
  uses: semgrep/semgrep-action@v1
  with:
    config: >-
      p/default
      p/java
      rules/no-rest-template.yaml

5. Semgrep Cloud

# 登入 Semgrep Cloud
semgrep login

# 雲端掃描(自動整合 GitHub PR)
semgrep ci

6. 與其他工具比較

特性 Semgrep Checkstyle SpotBugs
規則語言 YAML Pattern XML Config Java API
自訂規則 簡單 中等 困難
多語言 Java 為主 Java 為主
掃描速度 極快 較慢
AI 友善

7. 參考資源