当算法被篡改为 none 时,如何写测试验证漏洞?
解读
国内线上事故复盘里,“算法被篡改为 None”通常指:
- 配置中心或环境变量里本应是可调用对象(函数 / 类),被恶意或误操作写成 Python 字面量 None;
- 业务代码在调用处不做防御,直接
result = algo(*args),立即抛出TypeError: 'NoneType' object is not callable; - 该异常被最外层 try/except 吞噬,导致返回脏数据或降级逻辑,形成安全与资金风险。
面试官想考察的是:
- 能否把“安全漏洞”转化为“可自动化回归的测试用例”;
- 是否熟悉 pytest 的异常断言、fixture 注入、参数化、monkeypatch 等机制;
- 是否具备“攻击者视角”的测试设计能力(不仅要测 None,还要测其他可调用污染)。
知识点
- pytest 异常断言:
pytest.raises()及其match正则; - fixture 的依赖注入:用
@pytest.fixture把“算法”做成测试替身,方便统一篡改; - monkeypatch 的
setattr/setenv:在运行时把配置值换成 None,模拟外部篡改; - 参数化:
@pytest.mark.parametrize一次性覆盖 None、0、""、lambda:None 等“假可调用”; - 回归策略:对“调用点”做白盒测试,确保一旦为 None 就触发熔断/告警,而不是静默降级;
- 覆盖率门禁:让 CI 在 PR 阶段就拒绝“未命中防御分支”的代码。
答案
以下示例基于国内最常见的“微服务 + 配置中心”场景,假设业务代码如下:
# src/rebate.py
import os
from typing import Callable
def get_rebate_algo() -> Callable[[float], float]:
"""从配置中心拉取算法,默认返 0.95 折"""
algo_path = os.getenv("REBATE_ALGO") or "rebate:default_discount"
mod_name, func_name = algo_path.split(":")
mod = __import__(mod_name, fromlist=[func_name])
return getattr(mod, func_name)
def default_discount(amount: float) -> float:
return amount * 0.95
def calc_final_price(amount: float) -> float:
algo = get_rebate_algo()
# 这里一旦 algo 为 None 就会炸
return algo(amount)
测试目录 tests/test_rebate.py:
import os
import pytest
from src.rebate import calc_final_price, get_rebate_algo
class TestAlgoCorrupted:
"""验证算法被篡改为 None 的漏洞"""
@pytest.fixture
def amount(self):
return 100.0
def test_algo_none_via_env(self, monkeypatch, amount):
"""模拟配置中心把算法配成 None"""
monkeypatch.setenv("REBATE_ALGO", "builtins:None")
# 期望在“调用点”之前就能发现,而不是真正执行时
with pytest.raises(TypeError, match="'NoneType' object is not callable"):
calc_final_price(amount)
def test_algo_none_via_patch(self, monkeypatch, amount):
"""不依赖环境,直接 patch 函数返回 None"""
monkeypatch.setattr("src.rebate.get_rebate_algo", lambda: None)
with pytest.raises(TypeError):
calc_final_price(amount)
@pytest.mark.parametrize("bad_algo", [None, 0, "", list])
def test_defensive_programming(self, monkeypatch, amount, bad_algo):
"""如果业务已加防御,断言它抛出自定义异常或走降级"""
monkeypatch.setattr("src.rebate.get_rebate_algo", lambda: bad_algo)
# 假设业务已重构:algo 为 None 时抛 RebateError
with pytest.raises(RuntimeError): # 可换成自定义 RebateError
calc_final_price(amount)
CI 脚本 .gitlab-ci.yml(国内 GitLab 场景):
test:
stage: test
image: python:3.11
script:
- pip install -r requirements.txt
- pytest -q --cov=src --cov-fail-under=90
coverage: '/TOTAL.*\s(\d+%)$/'
要点说明
- 用
builtins:None让配置中心解析后拿到 None,最贴近真实攻击; - 两个测试分别覆盖“环境篡改”和“内存篡改”,确保无论哪条路径都被拦截;
- 若业务已做防御,则把
pytest.raises(TypeError)换成自定义异常,并补充分支覆盖; - 覆盖率门禁 90% 是阿里、字节等国内一线厂对“钱相关”模块的基线要求。
拓展思考
- 供应链污染:攻击者把
rebate.py文件本身换成空文件,导致get_rebate_algo返回 None。测试侧可引入tox+testcontainers,在干净容器里拉取最新依赖并做哈希校验。 - 动态字节码注入:用
unittest.mock.patch的new_callable把函数对象换成types.FunctionType外壳但内部为 None,测试需结合importlib.reload验证热加载场景。 - 性能漏斗:一旦算法为 None 就降级到本地兜底函数,测试需加
pytest-benchmark断言“降级路径”耗时 <10 ms,防止高并发雪崩。 - 合规留痕:国内金融项目要求“谁改了配置”可审计。测试可调用配置中心 OpenAPI 伪造一条“人为改 None”的日志,再断言告警通道(钉钉、飞书)收到关键字,实现“测试即审计”。