当 .env 文件被误提交时,如何让 CI 自动失败?

解读

在国内的 Python 项目里,.env 通常存放数据库密码、AK/SK、JWT 密钥等敏感信息。一旦推到 GitHub/Gitee/GitLab,轻则泄露隐私,重则引发合规事故。面试官问“如何让 CI 自动失败”,表面看是“检测文件”,实质考察三层能力:

  1. 安全意识:能否把“禁止入库”做成强制卡点,而不是口头规范;
  2. Pytest 生态与 GitLab CI/GitHub Actions 的联动:用 pytest 做“门禁”,而不是写 Shell 脚本;
  3. 工程化思维:失败要快、定位要准、修复成本要低,且不能拖慢流水线。

因此,答案必须给出“本地可复现、CI 零误报、一分钟内失败”的完整方案,并解释 pytest 在其中的定位。

知识点

  1. pytest 收集阶段钩子:pytest_collection_modifyitems 可在用例执行前统一做“仓库级”检查;
  2. pathlib / git ls-files:只扫描已提交(staged/committed)文件,避免把本地未提交文件当错误;
  3. 国内 CI 镜像:GitHub Actions 用 actions/checkout@v4,GitLab CI 用 registry.gitlab.cn 官方 Runner,均默认 shallow clone,要注意 git 命令兼容性;
  4. 失败策略:pytest.exit(msg, returncode=1) 可立即终止整个 Job,returncode 非零即 CI 失败;
  5. 合规基线:等保 2.0 /《个人信息保护法》要求“敏感信息不得落地”,因此检测规则需可审计、可版本化;
  6. 插件化:把检测逻辑写成独立 pytest 插件,供所有 Python 项目复用,符合国内大厂“中台”思想。

答案

步骤一:在项目根目录新建 tests/meta/test_forbidden_files.py,内容如下

import subprocess
import sys
from pathlib import Path
import pytest

FORBIDDEN = {".env", ".env.local", ".env.production"}   # 可按业务扩展

def test_no_env_committed():
    """如果任何禁止文件出现在最近一次 commit 中,则直接让 CI 失败。"""
    # 兼容 GitHub Actions / GitLab CI 的 shallow clone
    cmd = ["git", "ls-files"]
    try:
        committed = subprocess.check_output(cmd, text=True).splitlines()
    except subprocess.CalledProcessError:
        pytest.fail("无法执行 git ls-files,请确认 CI 已拉取仓库")

    found = [f for f in committed if Path(f).name in FORBIDDEN]
    if found:
        pytest.exit(
            reason=f"检测到敏感文件被提交:{', '.join(found)},请立即撤回并清理历史记录",
            returncode=1
        )

步骤二:在 pytest.ini 里把该用例设为“第一步”

[pytest]
testpaths = tests
python_files = test_*.py
addopts = -ra -q --tb=short

步骤三:CI 配置文件(以 GitHub Actions 为例)

name: gate
on: [push, pull_request]
jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0          # 需要完整历史才能 git ls-files
      - uses: actions/setup-python@v5
        with:
          python-version: "3.11"
          cache: pip
      - run: pip install pytest
      - run: pytest tests/meta/test_forbidden_files.py -v   # 先跑门禁
      - run: pytest                                           # 再跑正常测试

效果:

  1. 只要 .env 被 commit,pytest 在收集阶段就调用 pytest.exit,整个 Job returncode=1,GitHub 显示 ❌;
  2. 失败日志里会高亮打印“检测到敏感文件被提交:.env”,开发者一眼定位;
  3. 本地同样可执行 pytest tests/meta/test_forbidden_files.py,提前自检,符合“左移”理念。

拓展思考

  1. 历史清理:CI 失败后,仅删除文件再 push 并不能抹去泄露内容,需用 git filter-repo 或 BFG 重写历史;可再写一个 test_history_clean.py,扫描 git log --all --full-history -- "**/.env",若存在则再次失败,强制开发者走安全流程。
  2. 规则热更新:把 FORBIDDEN 列表做成 YAML 配置,放在独立仓库,pytest 插件运行时通过 urllib.request 拉取最新规则,实现“集团统一基线”。
  3. 与 pre-commit 互补:pre-commit 的 detect-private-key 只能检测内容,不能检测文件名;pytest 门禁可以兜底,防止绕过本地钩子直接 push。
  4. 性能优化:仓库超大时 git ls-files 仍很快;若担心,可在 CI 里加 if: contains(github.event.head_commit.modified, '.env') 做路径过滤,减少无谓 Job。
  5. 多语言复用:pytest 方案同样适用于 Node、Go 等混合仓库,只要保证 git ls-files 能列出即可,体现 Python/pytest 作为“测试 orchestrator”的跨栈能力。