在 CI/CD Pipeline 中,SAST(Static Application Security Testing)是一種重要的安全檢查步驟,可以幫助開發人員及早發現程式碼中的潛在安全漏洞。Semgrep 是一款功能強大的 SAST 工具,可以掃描程式碼並檢查各種安全問題,例如寫死的密碼、SQL Injection。
本文將介紹如何將 Semgrep 整合到 GitLab Pipeline 以進行 SAST 掃描。
semgrep:
image: returntocorp/semgrep
stage: test
script: semgrep ci
rules:
- if: $CI_PIPELINE_SOURCE == "web" # allow triggering a scan manually from the gitlab UI
- if: $CI_MERGE_REQUEST_IID # This rule triggers Semgrep if the scan is part of a merge request review process. The $CI_MERGE_REQUEST_IID variable holds the ID of the associated merge request, indicating its involvement.
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # This rule triggers Semgrep if the scan is run on the default branch (likely master or main). The $CI_COMMIT_BRANCH variable specifies the branch where the commit is being pushed, and comparing it to the $CI_DEFAULT_BRANCH variable checks for alignment.
variables:
SEMGREP_APP_TOKEN: $SEMGREP_APP_TOKEN
# To configure MR comments on gitlab.com, see <https://semgrep.dev/docs/semgrep-cloud-platform/gitlab-mr-comments/#enabling-gitlab-merge-request-comments>
GITLAB_TOKEN: $PAT
# Common large paths
node_modules/
build/
dist/
vendor/
.env/
.venv/
.tox/
*.min.js
.npm/
.yarn/
# Common test paths
test/
tests/
*_test.go
# Semgrep rules folder
.semgrep
# Semgrep-action log folder
.semgrep_logs/
將 Semgrep 整合到 GitLab Pipeline 後,可以將 SAST 掃描完全整合到開發工作流程中。在 Merge Request 中,開發人員可以直接看到掃描報告,並根據報告中的資訊及早修正程式碼中的安全漏洞。
以下是使用 Semgrep 的一些心得: