策略参考 — CAST 安全门禁
CAST 使用 conftest 配合 OPA Rego 策略来评估 SARIF 安全发现结果。这种方式用经过版本控制、可审计的策略替代了硬编码的 Shell 逻辑。
内置策略
CAST 内置三种策略,可通过 CAST_POLICY 变量选择:
| 策略 | 文件 | 阻断条件 | 适用场景 |
|---|---|---|---|
default |
policy/default.rego |
仅 CRITICAL | 生产流水线 |
strict |
policy/strict.rego |
CRITICAL + HIGH | 高安全要求项目 |
permissive |
policy/permissive.rego |
从不阻断 | 审计 / 初始接入 |
选择策略
GitHub Actions — 设置仓库变量:
Settings → Secrets and variables → Actions → Variables → New variable
Name: CAST_POLICY
Value: strict
GitLab CI — 设置 CI/CD 变量:
Settings → CI/CD → Variables → Add variable
Key: CAST_POLICY
Value: strict
若未设置 CAST_POLICY,则使用 default 策略。
门禁工作原理
- SARIF 生成作业(Semgrep、Trivy)将输出作为制品上传。
gate/cast-gate作业下载所有cast-sarif-*制品。- conftest 将每个 SARIF 文件与当前活跃策略进行评估。
- 若任何
deny规则触发,门禁作业以退出码 1 退出,阻止合并/MR。
SARIF 严重性与 conftest 级别的映射关系:
| 工具严重性 | SARIF level |
default |
strict |
|---|---|---|---|
| CRITICAL | error |
❌ 阻断 | ❌ 阻断 |
| HIGH | warning |
✅ 通过 | ❌ 阻断 |
| MEDIUM | warning |
✅ 通过 | ❌ 阻断 |
| LOW | note |
✅ 通过 | ✅ 通过 |
注意:Semgrep 将 ERROR 映射为error,WARNING 映射为warning。Trivy 在使用--severity CRITICAL,HIGH参数时,将 CRITICAL 和 HIGH 均映射为error。
编写自定义策略
若要覆盖 CAST 策略,请在仓库中创建 policy/ 目录并包含至少一个 .rego 文件。门禁作业会检测到该目录,并优先使用它,而非从 CAST 仓库获取策略。
your-repo/
├── policy/
│ └── my-policy.rego ← gates evaluate this
├── .github/workflows/
│ └── devsecops.yml
示例:仅对特定规则 ID 进行阻断
package main
import future.keywords.if
import future.keywords.in
BLOCKED_RULES := {"sql-injection", "hardcoded-secret", "eval-injection"}
deny[msg] if {
run := input.runs[_]
result := run.results[_]
result.ruleId in BLOCKED_RULES
msg := sprintf("Blocked rule %s: %s", [result.ruleId, result.message.text])
}
示例:仅对特定路径中的发现进行阻断
package main
import future.keywords.if
deny[msg] if {
run := input.runs[_]
result := run.results[_]
result.level == "error"
location := result.locations[_]
path := location.physicalLocation.artifactLocation.uri
not startswith(path, "test/") # ignore findings in test code
msg := sprintf("CRITICAL in %s: %s", [path, result.message.text])
}
在本地测试策略
安装 conftest:
brew install conftest # macOS
# or
curl -Lo conftest.tar.gz \
https://github.com/open-policy-agent/conftest/releases/download/v0.50.0/conftest_0.50.0_Linux_x86_64.tar.gz
tar xzf conftest.tar.gz && sudo mv conftest /usr/local/bin/
对 SARIF 文件运行测试:
# Test with default policy (blocks CRITICAL)
conftest test path/to/semgrep.sarif --policy policy/default.rego
# Test with strict policy (blocks HIGH + CRITICAL)
conftest test path/to/trivy.sarif --policy policy/strict.rego
# Test with all policies in directory
conftest test path/to/*.sarif --policy policy/
非零退出码表示策略已阻断——与在 CI 中的结果一致。