如何用 OWASP ZAP 扫描测试环境并导出结果到 pytest 报告?

解读

面试官问的是“把安全扫描结果塞进 pytest 报告”,而不是“跑一遍 ZAP 就行”。
国内主流场景是:

  1. 测试环境用 Docker-Compose 一键起,域名可能是 test.internal、网关走 80/443;
  2. CI 用 GitLab-Runner 或 Jenkins,节点无图形界面,必须 headless;
  3. 安全团队要求“每个迭代自动出报告,高危漏洞必须阻断流水线”;
  4. 测试报告要合并到 Allure 或 pytest-html,方便开发和审计一起看。

因此,答案必须覆盖:

  • 用 ZAP 官方 Python API(zaproxy 包)以守护进程模式启动;
  • 在 pytest 的 session 级 fixture 里触发扫描、等待完成、拉取 JSON 报告;
  • 把 JSON 映射成 pytest 自定义 “ZapItem” 测试用例,用 pytest.fail / pytest.skip 标记风险等级;
  • 最终让 Allure/pytest-html 里出现“安全测试” tab,且 CI 可基于 exit code 阻断。

知识点

  1. ZAP 守护进程:zap.sh -daemon -port 8090 -config api.key=ci123 -config api.addrs.addr.name=.*
  2. ZAP Python API:zap.core.access_url、zap.spider.scan、zap.ascan.scan、zap.core.jsonreport
  3. pytest fixture 作用域:session 级只跑一次,适合“全局扫描一次 -> 所有用例共享结果”;
  4. pytest 自定义 Item:继承 pytest.Item,在 runtest 里断言 “risk-high == 0”,失败即阻断;
  5. Allure 标签:@allure.feature("安全测试")、@allure.story("OWASP ZAP")、allure.attach(json, "zap-report.json", allure.attachment_type.JSON)
  6. 国内合规:>8 的高危漏洞必须当天修复,CI 需设置 --max-high=0;
  7. 性能优化:Docker 里加 -Xmx2g, spider 线程 10,ascan 强度 Insane 会打挂环境,建议 Medium。

答案

  1. 准备镜像
    docker pull owasp/zap2docker-stable
    写 docker-compose.yml,把 zap 跑在 8090,把被测服务跑在 8080,同一 network。

  2. 安装依赖
    pip install pytest zaproxy allure-pytest pydantic

  3. 目录结构
    tests/
    ├── conftest.py
    ├── test_zap.py
    └── zap_report.py

  4. conftest.py
    import pytest, json, time, os
    from zapv2 import ZAPv2

    @pytest.fixture(scope="session")
    def zap_client():
    zap = ZAPv2(proxies={"http": "http://zap:8090", "https": "http://zap:8090"}, apikey="ci123")
    yield zap

    @pytest.fixture(scope="session")
    def zap_report(zap_client):
    target = os.getenv("TEST_URL", "http://web:8080")
    zap_client.core.access_url(target)
    spider_id = zap_client.spider.scan(target)
    while int(zap_client.spider.status(spider_id)) < 100:
    time.sleep(2)
    ascan_id = zap_client.ascan.scan(target)
    while int(zap_client.ascan.status(ascan_id)) < 100:
    time.sleep(2)
    report = json.loads(zap_client.core.jsonreport())
    yield report

  5. zap_report.py
    import pytest, allure
    from pydantic import BaseModel

    class Alert(BaseModel):
    risk: str
    name: str
    url: str

    def pytest_collect_file(parent, path):
    if path.basename == "zap_report.json":
    return ZapFile.from_parent(parent, fspath=path)

    class ZapFile(pytest.File):
    def collect(self):
    data = json.loads(self.fspath.read_text("utf8"))
    for site in data.get("site", []):
    for alert in site.get("alerts", []):
    yield ZapItem.from_parent(self, name=alert["name"], alert=Alert(**alert))

    class ZapItem(pytest.Item):
    def init(self, *, alert, **kwargs):
    super().init(**kwargs)
    self.alert = alert

    def runtest(self):  
        if self.alert.risk in {"High", "Critical"}:  
            pytest.fail(f"[{self.alert.risk}] {self.alert.name} @ {self.alert.url}")  
    
    def repr_failure(self, excinfo):  
        return f"安全漏洞: {self.alert.name}"  
    
    def reportinfo(self):  
        return self.fspath, 0, f"zap: {self.alert.name}"  
    
  6. test_zap.py
    import json, os, pytest, allure

    @allure.feature("安全测试")
    def test_zap_high_vulnerabilities(zap_report, tmp_path):
    file = tmp_path / "zap_report.json"
    file.write_text(json.dumps(zap_report))
    allure.attach.file(str(file), name="zap-report", attachment_type=allure.attachment_type.JSON)
    high = [a for s in zap_report.get("site", []) for a in s.get("alerts", []) if a["risk"] in {"High", "Critical"}]
    assert len(high) == 0, f"发现 {len(high)} 个高危/严重漏洞"

  7. CI 调用
    docker-compose up -d
    pytest tests/ --alluredir=report
    allure generate report -o allure-report --clean

    高危>0 时 pytest exit 1,流水线阻断

拓展思考

  1. 增量扫描:用 zap.openapi.import_url 导入 swagger.json,只测新接口,时间从 30min 降到 5min;
  2. 认证扫描:在 fixture 里先调用 zap.authentication.set_authentication_method + zap.users.create_user,再带上 JWT cookie 做深度扫描;
  3. 多环境矩阵:用 pytest-xdist 把 zap 任务拆到 k8s 不同 namespace,并行扫 dev/sit/uat,报告聚合到 SonarQube 安全门;
  4. 漏洞闭环:解析 zap_report,自动在禅道/Jira 创建缺陷,缺陷模板带上“复现请求”字段,开发一键导入 Postman;
  5. 红蓝对抗:在 pytest 里再封装 “主动验证” 函数,对高危 alert 自动重放 payload,确认是否误报,减少 30% 噪音。