如何为 AST 变形测试写断言,验证注入点被正确修复?

解读

国内一线互联网公司的 Python 服务端/编译器/静态分析团队,常把“AST 变形测试”作为代码安全加固的核心手段:

  1. 先通过静态扫描定位潜在注入点(如 SQL 拼接、exec/eval、模板渲染等);
  2. 用自定义 ast.NodeTransformer 把危险节点替换成带参数化占位符的安全调用;
  3. 跑回归测试,确保功能等价且注入点确实被“修复”而非“绕过”。

面试官问“如何写断言”,考察三点:

  • 是否理解 AST 是不可变对象,变形后必须重新 compile;
  • 能否用 pytest 的断言内省能力,把“树形结构 diff”转成可读的失败信息;
  • 是否熟悉国内代码审计规范(如《GBT 34978-2017 信息安全技术 代码安全审计规范》),能把“修复”定义为“消除注入向量”而非“语法通过”。

知识点

  1. ast.dump(node, indent=2) 与 ast.unparse(node) 的差异:前者适合断言子树存在性,后者可读性高。
  2. pytest-ast-transform 插件(阿里内部 fork 版)提供的 ast_diff 工具,可生成统一 diff 并高亮危险节点。
  3. 参数化 fixture:用 @pytest.mark.parametrize("src,expected_sink", LOAD_FROM_CSV) 把“注入样例-修复后样例”批量喂给测试。
  4. 断言策略:
    a. 存在性断言:assert any(isinstance(n, ast.Call) and n.func.id == "safe_sql" for n in ast.walk(new_tree))
    b. 等价性断言:assert ast.unparse(new_tree) == expected_code
    c. 负向断言:assert not any(SQL_INJ_PATTERN.search(ast.get_source_segment(src, n)) for n in ast.walk(new_tree))
  5. 国内 CI 合规要求:测试失败必须输出 SARIF 格式报告,方便接入洞态/默安代码检查网关。

答案

# conftest.py
import ast, pytest, textwrap
from _pytest.assertion.util import assertrepr_compare

@pytest.fixture(scope="session", name="parse")
def _parse():
    def _inner(source: str) -> ast.Module:
        return ast.parse(textwrap.dedent(source).strip())
    return _inner

@pytest.fixture(scope="session", name="transform")
def _transform():
    from sql_safe import SafeSQLTransformer  # 团队内部实现
    def _inner(tree: ast.Module) -> ast.Module:
        transformer = SafeSQLTransformer()
        new_tree = transformer.visit(tree)
        ast.fix_missing_locations(new_tree)
        return new_tree
    return _inner

# test_ast_fix.py
import ast, pytest, re

SQL_INJ_RE = re.compile(r"\+.*request\.", re.S)

@pytest.mark.parametrize(
    "raw,expect_safe_call",
    [
        (
            """
            def query(request):
                sql = "SELECT * FROM user WHERE id=" + request.args.get("id")
                return db.execute(sql)
            """,
            "safe_sql"
        ),
    ],
    ids=["sqli_by_plus"]
)
def test_injection_fixed(parse, transform, raw, expect_safe_call):
    old_tree = parse(raw)
    new_tree = transform(old_tree)

    # 1. 负向断言:老代码里的注入模式必须消失
    old_src = ast.unparse(old_tree)
    assert SQL_INJ_RE.search(old_src), "老代码必须包含注入特征,否则测试用例无效"

    new_src = ast.unparse(new_tree)
    assert not SQL_INJ_RE.search(new_src), "修复后代码不得出现字符串拼接用户输入"

    # 2. 存在性断言:必须引入安全函数
    assert any(
        isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == expect_safe_call
        for node in ast.walk(new_tree)
    ), f"修复后代码必须调用 {expect_safe_call}"

    # 3. 等价性断言:compile 后字节码一致(功能不变)
    old_code = compile(old_tree, "<string>", "exec")
    new_code = compile(new_tree, "<string>", "exec")
    # 用 dis 比对字节码长度、常量表,略
    assert old_code.co_names == new_code.co_names, "函数对外依赖应保持一致"

运行 pytest -q -ra 后,若注入点未被替换,第二条断言会给出清晰的失败信息:

> assert not SQL_INJ_RE.search(new_src)
AssertionError: 修复后代码不得出现字符串拼接用户输入
assert None is not None

国内面试官希望看到“失败即合规证据”,因此把正则失败信息直接落到 Allure 报告,方便审计部拉取。

拓展思考

  1. 增量场景:在微服务仓库里,只对新 diff 中的函数做 AST 变形,断言范围缩小到 git diff 涉及的 ast.FunctionDef。pytest 可通过 --diff-filter=AM` 拿到文件列表,配合自定义 collection 插件动态生成测试项。
  2. 多语言统一:国内很多团队是 Python + Go 混合仓库,可用 tree-sitter 把 Go 的 AST 转成通用 JSON,pytest 侧用 jsonpath-ng 写跨语言断言,实现“一份用例,多端复用”。
  3. 灰度验证:在阿里安全红线流程中,AST 修复后需回灌流量做“影子执行”。pytest 侧可启动两个进程(老代码 / 新代码),用 pytest-xdist 的 --dist=loadscope 把同一参数化用例发到不同 worker,最后用 assert out1 == out2 做输出一致性校验,实现“零回归”上线。