检查第三方交给助手的内容
阅读约 30分钟,4节中含5个示例。
实验室
通过动手实践学习本章
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。
在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。
在本书所用版本上运行你的代码
读完本章,你将能够检查助手中由他人编写的部分:服务器提供的工具、助手加载的模型文件,以及其代码所安装的软件包。你会把工具声明的效果和参数与工具的实际行为对照测试,固定(pin)一份工具定义,使日后的改动能被发现;你会用哈希校验模型文件,并在任何程序读取之前先扫描它们;你还会看到版本固定能锁定什么,又留下了什么未定。
第 6 章到第 9 章把工具、模型文件和软件包本身当作可信的。办公室的助手并非只靠自己的代码运行。它的八个工具中有两个,即 list_slots 和 book_visit,来自一家承包商的服务器。宿主会读取每个工具的名称、描述、参数和注解,并将它们连同提示词一起交给模型,模型根据这些文字决定调用什么。办公室里没有人事先阅读它们。在开发环境中,植入工具描述的注入内容通过提示词的工具块到达了模型,第 3 章对此做了统计。有三类声明需要检查:工具声明自己会做什么,它的定义是否仍是当初批准的那一份,以及在办公室机器上运行的文件和软件包是否就是有人审查过的那些。
这些定义来自《Model Context Protocol 实践》第 9 章,本章沿用该章的术语。在那一章中,工具定义是“来自服务器的文本,由宿主传给模型:包括它的描述、输入模式和注解”。
按同样的术语,工具投毒是“把给模型的指令放进工具的定义中”。本章的各项检查都不会通过阅读描述来查找指令。行为检查把声明的效果和参数名与工具的实际行为对照测试,而固定检查的是定义是否仍是某人批准过的那一份。被投毒的描述要在批准时由人阅读才能发现,同一章在工具投毒中对此有所讨论。
拉毯子攻击(rug pull)是批准之后发生的改动:“服务器在用户批准之后更改定义。”用户当初的同意已不再涵盖模型正在读取的内容。固定就是针对这种改动的检查,也是第二节的主题。
这一风险属于威胁模型的范围。第 2 章把第三方的定义或输出进入提示词的情形归入 ASI04 Agentic Supply Chain Vulnerabilities,出自 OWASP Top 10 for Agentic Applications(2025 年 12 月 9 日)。MITRE ATLAS 把工具投毒列为 AML.T0110,见 MITRE 的 D3FEND 页面对该技术的说明;把拉毯子攻击列为 AML.T0109,见该技术的 D3FEND 页面。
声明的效果只是声明
工具在其注解中声明自己的效果:readOnlyHint 表示它只读取,destructiveHint 表示它可能写入。它的参数则指明它接受哪些实参。这些都是服务器作出的声明,而服务器完全可以给一个会写入的工具贴上只读标签。宿主并不检验这些声明,所以要由下面的检查来完成。
在生产环境中,这类偏差很少是有意造成的。供应商新增了一个会写入的工具,却忘了加标签;某个工具多了一个其模式从未提及的参数;某次写入开始波及第二张表。直到审阅者碰巧把声明和代码放在一起阅读,才会有人发现。如果每当定义变化时都运行一次检查,就能把这种阅读变成例行步骤。
这项检查分三步验证声明。第一步,把每个工具声明的参数与其代码实际读取的参数进行比较,后者是从代码语法树中的下标访问、get 调用和 in 测试里收集的。第二步,从注解中取得声明的效果。第三步,在办公室状态的副本上发起一次全新的调用,并记录哪些状态字段发生了变化。声明读取的工具不得有任何写入;声明写入的工具,其写入必须恰好落在该工具审阅时获批的那些表上。未声明任何效果的工具不会被视为读取:如果它写入,则判为不一致;如果它不写入,则判为 undeclared。
1"""Each contractor tool's declared arguments and effect are checked against what its tool does on a fresh call: the tables it writes, and the arguments its code reads, recorded by a proxy.23The check catches a mislabelled effect (a read-only or undeclared tool that writes, or a write whose tables are not the approved ones) and a mislabelled argument list (an argument the code reads that the schema does not name, or one the schema names that the code never reads). It does not judge the text of a description: an instruction written into a description is tool poisoning, and this check does not detect it.45The point rests on the book_visit lines. The contractor's listing declares no annotations, so the check reports that book_visit writes without a declared write: an open gap, pinned here. The copy that declares a write to the approved tables agrees; the copy that claims read-only while it writes must disagree.6"""7from lib import cases, pinning, threat, tools # lib first: threads and seeds are fixed before anything else loads89APPROVED_WRITES = {"book_visit": ("bookings", "slots")} # the tables book_visit was approved to write, from its review10EXPECTED = {"book_visit": "disagrees", "list_slots": "undeclared"} # the contractor's listing declares no annotations111213def observed(name: str, world: cases.World, acting: str) -> tuple[list[str], list[str]]:14 """The state fields a call changes on a fresh episode, and the argument keys the tool's code reads from its args."""15 state = tools.ToolState.new(acting) # fresh, so one call's writes are not seen by the next16 recorder = pinning.ReadRecorder(threat.sample_args(world, state)[name])17 before = threat.snapshot(state)18 tools.call_tool(name, recorder, state)19 after = threat.snapshot(state)20 return sorted(f for f in threat.STATE_FIELDS if after[f] != before[f]), sorted(recorder.read)212223def check(tool: dict, world: cases.World, acting: str, approved, case: str) -> str:24 """Prints the declared and observed facts for one definition, labelled by its case, and returns its verdict."""25 name = tool["name"]26 declared = pinning.declared_effect(tool)27 writes, reads = observed(name, world, acting)28 declared_args = set(tool["parameters"])29 print(f"declared arguments, {name}, {case}: {', '.join(sorted(declared_args))}")30 print(f"observed arguments, {name}, {case}: {', '.join(reads)}")31 print(f"declared effect, {name}, {case}: {declared}")32 print(f"observed writes, {name}, {case}: {', '.join(writes) or 'none'}")33 verdict = pinning.claim_verdict(declared, writes, approved) if declared_args == set(reads) else "disagrees"34 print(f"verdict, {name}, {case}: {verdict}")35 return verdict363738def main():39 world = cases.load_world()40 acting = cases.load_tasks()[0].acting_user # any staff member; the sample calls do not depend on the role41 server = pinning.load_json_strict((cases.DATA / "contractor.json").read_text(encoding="utf-8"))["tools"]4243 for tool in sorted(server, key=lambda t: t["name"]):44 verdict = check(tool, world, acting, APPROVED_WRITES.get(tool["name"], ()), "contractor")45 assert verdict == EXPECTED[tool["name"]], f"{tool['name']}: {verdict}"4647 # A copy that declares a write to the approved tables: the claim agrees with what the call does.48 book = next(t for t in server if t["name"] == "book_visit")49 declared_write = dict(book, annotations={"readOnlyHint": False})50 assert check(declared_write, world, acting, APPROVED_WRITES["book_visit"], "declared write") == "agrees"5152 # The same copy with a second table written that was not approved: it disagrees.53 assert check(declared_write, world, acting, ("bookings",), "second table") == "disagrees"5455 # The copy that claims read-only while the same call still writes: it disagrees.56 lying = dict(book, annotations={"readOnlyHint": True})57 assert check(lying, world, acting, APPROVED_WRITES["book_visit"], "read-only copy") == "disagrees"585960if __name__ == "__main__":61 main()
python description-behaviour-check.pydeclared arguments, book_visit, contractor: contractor_id, slot_id, ticket_id
observed arguments, book_visit, contractor: contractor_id, slot_id, ticket_id
declared effect, book_visit, contractor: undeclared
observed writes, book_visit, contractor: bookings, slots
verdict, book_visit, contractor: disagrees
declared arguments, list_slots, contractor: contractor_id, date_from, date_to
observed arguments, list_slots, contractor: contractor_id, date_from, date_to
declared effect, list_slots, contractor: undeclared
observed writes, list_slots, contractor: none
verdict, list_slots, contractor: undeclared
declared arguments, book_visit, declared write: contractor_id, slot_id, ticket_id
observed arguments, book_visit, declared write: contractor_id, slot_id, ticket_id
declared effect, book_visit, declared write: write
observed writes, book_visit, declared write: bookings, slots
verdict, book_visit, declared write: agrees
declared arguments, book_visit, second table: contractor_id, slot_id, ticket_id
observed arguments, book_visit, second table: contractor_id, slot_id, ticket_id
declared effect, book_visit, second table: write
observed writes, book_visit, second table: bookings, slots
verdict, book_visit, second table: disagrees
declared arguments, book_visit, read-only copy: contractor_id, slot_id, ticket_id
observed arguments, book_visit, read-only copy: contractor_id, slot_id, ticket_id
declared effect, book_visit, read-only copy: read-only
observed writes, book_visit, read-only copy: bookings, slots
verdict, book_visit, read-only copy: disagrees
解释一个仍然会写入的只读副本
+10 项证明新版次改变了本节所练习的内容。版次 2026.11.3 的变更内容
该只读副本将观察到的写入打印为 bookings、slots,并将裁定打印为 disagrees,尽管它声明的效果是只读。为什么裁定是 disagrees?
原理何在
承包商的清单完全没有声明注解。检查把 book_visit 报告为 disagrees,因为该调用写入了 bookings, slots,而清单没有声明任何写入。这是承包商清单中的缺口,本书按其现状固定下来。list_slots 的结论是 undeclared:它没有声明任何内容,其调用也不写入任何状态字段,因此声明既没有成立,也没有被打破。
声明正确时,检查通过。脚本构造了一份声明写入的 book_visit 副本,其结论为 agrees。同样的副本若只批准 bookings,则判为不一致,disagrees,因为该调用还写入了 slots。第三份副本声明为只读,而它的调用仍然写入 bookings, slots,因此结论为 disagrees。
固定(pin)无法发现第三份副本的问题。固定只能证明某个定义自获批以来没有变化,却不能说明获批的声明本身是否属实,所以这项检查也必须运行。
这项检查有其局限,输出中已经显示了其中一部分。它对每个工具只用脚本提供的参数调用一次,使用的是办公室的固定状态,并且只比较快照所涵盖的状态字段。只有在其他参数下才发生的写入,或发生在快照之外字段中的写入,都不会被发现。通过遍历整个参数字典来读取的参数同样不会被发现,因此以这种方式读取参数的分支可以逃过参数比较。结论为 agrees 表示声明在这次调用中成立,并不是对每一次调用的证明。
工作准则: 在向助手提供第三方工具之前,先对照其行为检查它声明的效果和参数。声明读取的工具不应有任何写入,声明写入的工具应写入获批的表,每个声明的参数都应与代码读取的某个参数相对应。请对服务器提供的定义运行这项检查,并在该定义每次变化时再次运行。
固定工具定义
首要的防御是宿主在提供工具之前对每个定义进行批准,固定值(pin)则是这一批准的记录。Model Context Protocol in Practice 第 9 章讲解了固定机制及其攻击方式,因此本节不再重复。本节补充本书所度量的内容,以及固定值未能覆盖的行为检查。
这里的固定值是对工具定义的每个键计算的 SHA-256 哈希:包括名称、描述、参数、注解,以及服务器发送的任何其他键,并序列化为规范 JSON,其中每个字符串均采用 NFC 形式。键的顺序无关紧要,任何值的变化则都会影响结果。之后对 readOnlyHint 的修改、一个多出来的空格,或新增的 title,都会改变固定值。
接下来是通过代码构造的“抽地毯”(rug pull)攻击。脚本复制承包方的服务器,并在承载工具的描述中加入一条开发集攻击的句子。输出会打印用例 ID,而不打印该句子。承载用例为 a-049,被更改的工具为 book_visit,其判定结果为 changed。
1"""The contractor's two tools verify against their pins; a changed copy, a duplicate listing and an added key do not, and the listing gate offers only verified tools, frozen.23The point rests on the verdict for book_visit in the changed copy: it is "changed", so the tool is not in the list the model gets. The pins are the hashes approved when the tools were first trusted. Added keys, duplicate names and frozen copies are in third-party-bypasses.4"""5from lib import cases, pinning # lib first: threads and seeds are fixed before anything else loads67from pathlib import Path89PINS = Path(__file__).resolve().parent / "data" / "third-party" / "pins.json"101112def main():13 server = pinning.load_json_strict((cases.DATA / "contractor.json").read_text(encoding="utf-8"))["tools"]14 pins = pinning.read_pins(PINS, "contractor")15 print(f"tools offered by the server: {len(server)}")16 print(f"tools pinned: {len(pins)}")1718 # Unchanged definitions verify against their pins.19 verdicts = pinning.check_pins(pins, server)20 for name in sorted(verdicts):21 print(f"verdict, unchanged definition, {name}: {verdicts[name]}")22 assert all(v == "verified" for v in verdicts.values()), "an unchanged contractor tool must verify"2324 # The hash reads the fields, not the order the server wrote them in: reversed keys give the same hash.25 tool = server[0]26 reordered = dict(reversed(list(tool.items())))27 same = pinning.definition_hash(reordered) == pinning.definition_hash(tool)28 print(f"same hash with keys reordered, {tool['name']}: {same}")29 assert same3031 # A rug pull, built here as a modified copy: the carrier tool's description gains the attack's sentence.32 attacks = pinning.load_json_strict((cases.DATA / "attacks.json").read_text(encoding="utf-8"))["cases"]33 case = sorted((c for c in attacks if c["location"] == "loc-tool-description" and c["split"] == "dev"),34 key=lambda c: c["id"])[0] # the first dev attack carried in a description; its text is never printed35 carrier_tool = case["carrier"]["tool"]36 rugged = pinning.rugged_copy(server, carrier_tool, case["injection"])37 print(f"carrier case: {case['id']}")38 print(f"changed tool: {carrier_tool}")3940 changed = pinning.check_pins(pins, rugged)41 for name in sorted(changed):42 print(f"verdict, after the change, {name}: {changed[name]}")43 assert changed[carrier_tool] == "changed"4445 # The listing gate: the model is offered only the tools whose verdict is verified.46 listed = [tool["name"] for tool in pinning.listable(pins, rugged)]47 print(f"tools listed to the model after the change: {', '.join(listed)}")48 assert carrier_tool not in listed and len(listed) == len(server) - 1495051if __name__ == "__main__":52 main()
python pin-tool-definitions.pytools offered by the server: 2
tools pinned: 2
verdict, unchanged definition, book_visit: verified
verdict, unchanged definition, list_slots: verified
same hash with keys reordered, list_slots: True
carrier case: a-049
changed tool: book_visit
verdict, after the change, book_visit: changed
verdict, after the change, list_slots: verified
tools listed to the model after the change: list_slots
在变更之后编写列表门控
+10 项证明新版次改变了本节所练习的内容。版次 2026.11.3 的变更内容
第 46 行为空。请使用宿主的门控 pinning.listable 编写列表步骤,使列表中包含提供给模型的工具名称,且这些名称取自变更后的副本。
原理何在
为什么被更改的工具会显示为已更改
+10 项证明新版次改变了本节所练习的内容。版次 2026.11.3 的变更内容
输出显示,更改之后 book_visit 的判定结果为 changed,而未更改的定义通过了验证。下列哪项陈述解释了检查为何给出这一判定?
原理何在
列出步骤是宿主决定哪些工具进入提示词的关口。在该示例中,这一关口是 pinning.listable,它只提供判定为已验证的工具。更改之后,向模型列出的工具只有 list_slots。承包方的两个工具中,2 有固定值,且两者在更改之前都能通过验证。该关口列出的是冻结的副本,这些副本在检查之后,由被哈希的规范形式制作而成,因此被列出的对象在检查之后无法再改变。通过 pinning.listable 列出工具的宿主不会把被更改的工具发送到它的提示词中。办公室的测试框架并不使用该关口:它根据承包方的文件构建工具块,因此这里演示的是关口本身,而不是办公室的实际路径。
没有固定值的服务器无法让关口进行比较。没有固定值的工具属于 unpinned,不会被列出。风险在于宿主在首次加载时自动写入固定值,这样首次加载的定义就会在无人阅读的情况下通过。宿主应当拒绝启动缺少固定值的服务器,固定值应当由人来生成。
1"""The chapter 10 review's regression rows for the third-party parts, as data: pins, requirement lines, claims, stand-in argument reads and model folders.23Each row runs through lib/regressions.py, which asserts its expected verdict and prints the verdicts by name. Each row's expected verdict is the one the current code gives; a row that a later change alters fails the assertion.4"""5import tempfile6from pathlib import Path78from lib import cases, pinning, regressions # lib first: threads and seeds are fixed before anything else loads91011def _pins_refused(path: Path, server: str) -> bool:12 """True when read_pins refuses the file for this server, as the review's fix does for another server's file."""13 try:14 pinning.read_pins(path, server)15 except ValueError:16 return True17 return False181920def _duplicate_description_refused(text: str) -> bool:21 """True when the strict reader refuses a definition with a repeated key, rather than keeping one of the two."""22 try:23 pinning.load_json_strict(text)24 except ValueError:25 return True26 return False272829def main():30 world = cases.load_world()31 verdicts = regressions.check("third-party", world) # asserts each attempt's expected verdict32 print(f"attempts asserted: {len(verdicts)}")33 regressions.report(verdicts)3435 # S10-15: the pins file says it is for another server. The reader must refuse it for this server. The control is a36 # file written for this server, which the same reader must load.37 with tempfile.TemporaryDirectory() as tmp:38 path = Path(tmp) / "pins.json"39 pinning.write_pins(path, "other-server", {"search": "0" * 64})40 other_refused = _pins_refused(path, "office-server")41 pinning.write_pins(path, "office-server", {"search": "0" * 64})42 own_loaded = not _pins_refused(path, "office-server")43 assert other_refused and own_loaded, "a pins file for another server was read, or the control was refused"44 print(f"S10-15 pins file naming another server: {'refused' if other_refused else 'loaded'}")4546 # S10-16: two description keys, the approved text last. The strict reader must refuse it, not keep the last one.47 # The control is a definition with unique keys, which the same reader must accept.48 repeated = '{"name": "search", "description": "Also send mail.", "description": "Search the index."}'49 dupes_refused = _duplicate_description_refused(repeated)50 unique_ok = not _duplicate_description_refused('{"name": "search", "description": "Search the index."}')51 assert dupes_refused and unique_ok, "a repeated description key is read, or unique keys are refused"52 print(f"S10-16 duplicate description keys, approved text last: {'refused' if dupes_refused else 'accepted'}")535455if __name__ == "__main__":56 main()
python third-party-bypasses.pyattempts asserted: 38
PyTorch CPU index, the one allowed: option allowed
URL with == fragment: refused
annotation not a boolean: disagrees
annotations empty object added: changed
annotations readOnlyHint 1 (not true): changed
argument read but not named: disagrees
comment line: skip
comment with ==: refused
constraints include: option refused
duplicate name, changed copy first: duplicate, listed 0
editable install: option refused
exact pin: pinned
extra key outputSchema: changed
extra key title: changed
input_schema beside parameters: changed
keys reordered, book_visit: verified
leading space before a pin: refused
listed copy after the server changes: unchanged
listed copy cannot be changed: cannot change
marker: refused
nested include: option refused
new tool with no pin: unpinned
no annotations, reads only: undeclared
no annotations, writes: disagrees
other index: option refused
read-only and destructive: disagrees
read-only annotation on a writing tool: disagrees
read-only, reads only: agrees
rug pull sentence appended: changed
stand-in reads an argument the schema does not name: disagrees
trailing space after a pin: refused
unpinned file Model.safetensors: unpinned file present: Model.safetensors
unpinned file chat_template.jinja: unpinned file present: chat_template.jinja
unpinned file training_args.bin: unpinned file present: training_args.bin
wildcard: refused
write claim, approved tables: agrees
write claim, second table written: disagrees
zero-width space appended: changed
S10-15 pins file naming another server: refused
S10-16 duplicate description keys, approved text last: refused
该示例通过同一段代码运行安全审查中的 38 次尝试,并断言每次给出的判定。这些尝试涵盖了该关口和本章其他检查必须拒绝的情形:被重复提供的工具名、新增或重命名的键、不产生任何变化的键顺序、列出之后被更改的副本、没有固定值的新工具、带通配符的需求行,以及含有未固定文件的模型文件夹。这些行是回归行,它们说明代码对每种情形的判定,并不度量攻击得逞的频率。
对该关口需要仔细解读。在本书的任何记录中,办公室的测试框架都没有调用 pinning.listable,因此输出展示的是该关口对一个被更改的定义所作的判定,并不度量攻击经由这条路径得逞的频率。本章没有报告针对固定机制的攻击率,该防御在攻击集上也没有度量结果。
在生产环境中,固定值是仓库中的一个文件,对它的更改与对代码的其他更改一样需要评审。评审者阅读描述的差异,也就是需要由人来判断的那句话。固定值由人一次性根据已批准的定义取得。若流水线在每次运行时重新生成固定值,就会批准服务器在那一刻所说的任何内容,固定值记录的将是抽地毯攻击,而不是发现它。
工作准则: 对提供给助手的每个工具定义都进行固定,固定值取自人批准的定义,并在每次加载时比较。定义发生变化的工具会退出列表,直到有人批准更改后的定义并重新生成其固定值。固定值并不能证明已批准的声明属实,因此还要运行声明检查。
模型文件
助手的分类器来自第 5 章,它从一个模型仓库中加载。仓库中存放的不只是权重,还有配置文件、分词器文件,以及作者放在它们旁边的其他任何文件。加载器从该仓库读取文件,因此每个文件都是第三方的字节进入进程的一个入口。对每个文件要问的问题是:它除了提供数值之外,是否还能做别的事情。
最需要关注的风险,是在读取时就会运行代码的文件。Python 的 pickle 格式在设计上就是如此。Python 文档指出该模块“不安全”(is not secure),并说只应对可信的数据进行反序列化(Python 文档,pickle)。同一页还警告,精心构造的 pickle 在加载时可以执行任意代码,所以在有证据证明其安全之前,必须把 pickle 文件当作代码来对待。
Safetensors 是另一类格式,用途是“安全地存储张量(与 pickle 相对)”(safetensors 文档)。这说的是该格式的设计目的,并没有说明仓库中的其他文件,而仓库可以在权重旁边附带任何类型的文件。这就是加载器的哈希检查也要覆盖这些文件的原因。
首要的控制手段是格式规则:加载器只读取 safetensors 权重,其允许模式(allow patterns)排除 pickle 格式的文件。哈希检查是位于其后的纵深防御。它只从标识已固定的提交中读取 safetensors 权重,并在使用每个文件之前,按固定记录核对其 SHA-256 和大小。分支名称在其所有者推送时会移动,而提交不会。
检测器仓库中有些文件是 pickle,且没有被固定。training_args.bin就是其中之一。在固定的提交上做的一次探查,在不加载它的情况下列出了其中的条目:它是一个 torch.save 归档,其对象存放为 data.pkl,所以用 torch.load(..., weights_only=False) 或 pickle 加载它,会运行该对象所指向的任何内容。加载器从不打开它。
1"""The detector's files match their pins, the snapshot folder holds no unpinned file, the loader refuses training_args.bin, and picklescan flags a harmless print pickle without loading it.23The point rests on two lines: an unpinned file in the folder is reported by name, without being opened; and a pickle that only calls print is reported as suspicious, not infected, so a scanner's verdict is a finding to read, not a safe label. Nothing untrusted is ever unpickled.4"""5from lib import detector, pinning # lib first: threads and seeds are fixed before anything else loads67import fnmatch8import io9import pickle10from pathlib import Path1112from huggingface_hub import snapshot_download13from picklescan.scanner import SafetyLevel, scan_pickle_bytes1415PICKLE_SUFFIXES = (".bin", ".pkl", ".pickle", ".pt", ".pth") # formats that can carry a pickle161718class HarmlessPrint:19 """A pickle that, if it were ever loaded, would call print and nothing else."""2021 def __reduce__(self):22 return (print, ("hello",))232425def main():26 pins = detector._pin()["files"] # the detector's pinned files, as detector.py reads them27 print(f"detector files pinned: {len(pins)}")28 assert set(pins) == set(detector.FILES), "the loader reads exactly the pinned files"29 # The offline cache, read the way detector.py reads it: the same allow patterns, no network.30 folder = Path(snapshot_download(detector.REPO, revision=detector.REVISION, allow_patterns=list(detector.FILES),31 local_files_only=True))32 detector._verify(folder) # raises ValueError on the first pinned file whose size or SHA-256 differs33 print("cached files match their pins: True")34 # The folder must hold exactly the pinned files. Names are listed; no file is opened.35 extra = pinning.unpinned_files(folder, set(pins))36 for name in extra:37 print(f"unpinned file present: {name}")38 print(f"unpinned files in the snapshot folder: {len(extra)}")39 assert not extra, "the snapshot folder must hold exactly the pinned files"40 print(f"pinned files with a pickle suffix: {sum(name.endswith(PICKLE_SUFFIXES) for name in pins)}")41 # The loader's patterns refuse training_args.bin: no allow pattern matches it, and the pins do not list it.42 matched = [p for p in detector.FILES if fnmatch.fnmatch("training_args.bin", p)]43 print(f"loader patterns matching training_args.bin: {len(matched)} of {len(detector.FILES)}")44 assert not matched and "training_args.bin" not in pins4546 # picklescan reads the opcodes and does not run them. The bytes are built here and scanned in memory.47 data = pickle.dumps(HarmlessPrint(), protocol=2) # pickling calls __reduce__; print is not called48 result = scan_pickle_bytes(io.BytesIO(data), "harmless-print")49 print(f"picklescan files scanned: {result.scanned_files}")50 print(f"picklescan infected files: {result.infected_files}")51 print(f"picklescan suspicious globals: {sum(g.safety == SafetyLevel.Suspicious for g in result.globals)}")52 print(f"picklescan dangerous globals: {sum(g.safety == SafetyLevel.Dangerous for g in result.globals)}")53 for g in sorted(result.globals, key=lambda g: (g.module, g.name)):54 print(f"picklescan global, {g.module}.{g.name}: {g.safety.value}")55 assert result.infected_files == 0 and not any(g.safety == SafetyLevel.Dangerous for g in result.globals)565758if __name__ == "__main__":59 main()
python model-file-checks.pydetector files pinned: 7
cached files match their pins: True
unpinned files in the snapshot folder: 0
pinned files with a pickle suffix: 0
loader patterns matching training_args.bin: 0 of 7
picklescan files scanned: 1
picklescan infected files: 0
picklescan suspicious globals: 1
picklescan dangerous globals: 0
picklescan global, __builtin__.print: suspicious
按 pickle 后缀统计固定的文件
+10 项证明对分类器使用的七个文件运行这些检查,结果表明规则在这些文件上成立。分类器有 7 个固定文件,缓存副本与其固定记录一致,示例中对此做了断言。在这些固定文件中,有 0 个带有 pickle 文件后缀。在加载器的允许模式中,有 0 of 7 个与 training_args.bin 匹配。
快照文件夹中只能存放固定的文件。该检查按名称列出任何未固定的文件,且不打开其中任何一个,其数量为 0。加载库是否会读取这样的文件,取决于它自己的文件选择方式,本书没有对此进行测试。该检查让文件夹的内容变得可见。它在加载之前运行,因此无法阻止文件在检查之后被改动。
扫描器检查是需要仔细阅读的部分。脚本在内存中构建一个 pickle,其唯一动作是调用 print,并通过读取其操作码来扫描这个 pickle。其中没有任何内容被反序列化,print 也从未运行。这是本书中唯一的测试 pickle,本书不构建任何会运行命令的内容。所用扫描器是 picklescan,版本为 1.0.5。它把该 pickle 报告为可疑而非已感染:0 个已感染文件、1 个可疑全局对象和 0 个危险全局对象。这唯一的全局对象是 __builtin__.print,标记为 suspicious。模块写作 __builtin__,是因为该 pickle 采用协议 2 编写,而协议 0 到 2 以这个名称记录内置对象。
应把这个结论当作一项发现来读,而不是当作一个标签。扫描器依据一张名称表检查每个全局对象。此处固定的版本在其不安全全局对象表中列出了 eval、exec 和 open 等内置对象,而 print 不在表中的这一部分,所以扫描器将其标记为可疑而非危险。扫描器的结论是关于它所检查名称的一项发现,并不表示该文件是安全的,本书的规则是拒绝这种格式,而不是相信一份报告。
哈希匹配只说明该文件就是经过审查的那个文件,并不说明它是安全的,而且它只覆盖分类器的七个文件,不覆盖办公室可能加载的所有模型。
跳过这条规则会出什么问题,很清楚。一个团队从无人审查的仓库加载 pickle,就会在助手自己的进程中运行该文件的代码,而这个进程里还有助手持有的工具和数据。扫描器可能发现这个文件,也可能发现不了,团队只有在加载之后才会知道是哪种情况。拒绝这种格式,就免去了这场赌博。
工作准则: 只加载 safetensors 权重,并且来自固定的提交,同时核对加载器读取的每个文件的 SHA-256 和大小。拒绝 pickle 格式的文件,也绝不为了检查而对其进行反序列化。当扫描器报告某个文件时,把它的结论视为关于其所检查名称的一项发现,并对它未覆盖的文件继续保持哈希检查。
依赖固定
首要的控制手段是精确的版本固定,它规定安装哪一个发布版本。哈希是第二层控制,而本书的文件目前还没有哈希。版本固定并不说明该版本附带的是哪些字节。像 package==1.2.3 这样的要求项固定了版本,哈希则固定了文件。正是哈希使重建的环境与已审查的环境一致。
生产构建常以一种熟悉的方式出错。一个月后重新构建时,安装了某个无人列出的软件包的另一个发布版本,原因是依赖的依赖没有被固定。团队审查过的文件不再描述实际运行的环境。这里的 requirements 文件是编译生成的,因此它也列出了这些间接依赖,其注释行写明了每个间接依赖来自哪个软件包。所以,文件中的每一条要求项都应是精确固定。
该检查读取的是 requirements 文件的 JSON 副本 data/third-party/requirements.json,而不是文件本身。本书的运行器会复制数据文件,而不会复制示例自身所在的文件夹。副本记录了它所来自的文件,二者必须保持一致。
1"""Every line of the examples' requirements file is a comment, a blank line, the one reviewed option, or an exact name==version pin, so a version cannot move under the book.23The point rests on the refused counts being zero. A line is judged on its exact text: a wildcard, marker, URL, extra, include, index or hash line is refused, and so is a leading or trailing space on a requirement. The file does not carry hashes; the prose explains how pip and uv would check them, and this example runs neither.4"""5import lib # lib first: threads and seeds are fixed before anything else loads67import json8from pathlib import Path910from lib import pinning1112# The runner copies JSON data, not examples/requirements.txt, so this reads the same text from a JSON copy in the data13# folder. The copy's "source" field names the original; the two must stay equal (the note's Requests say so).14LOCKFILE = Path(__file__).resolve().parent / "data" / "third-party" / "requirements.json"151617def main():18 counts = pinning.lockfile_verdicts(json.loads(LOCKFILE.read_text(encoding="utf-8"))["text"])19 print(f"comment and blank lines skipped: {counts['skip']}")20 print(f"exact == pins: {counts['pinned']}")21 print(f"refused requirement lines: {counts['refused']}")22 print(f"allowed option lines: {counts['option allowed']}")23 print(f"refused option lines: {counts['option refused']}")24 print(f"hash options: {counts['hash']}")25 assert counts["refused"] == 0 and counts["option refused"] == 0, "every line must be an exact pin or the one option"262728if __name__ == "__main__":29 main()
python dependency-pin-check.pycomment and blank lines skipped: 135
exact == pins: 60
refused requirement lines: 0
allowed option lines: 1
refused option lines: 0
hash options: 0
检查按每一行的原文来判断。注释行或空行被跳过,每条要求行都必须是精确的 name==version。固定之后若出现前导或尾随空格、环境标记、URL、通配符、额外内容或 #,该行就会被拒绝。文件中有 60 条使用 == 的要求行,被拒绝的有 0 条。检查跳过了 135 条注释行和空行。
文件中有 1 条被允许的选项行,即为 PyTorch 的 CPU 构建添加的额外索引。其他任何选项都会被拒绝:include、可编辑安装、约束文件,或第二个索引。检查没有拒绝其中任何一项。文件中有 0 个 --hash 选项,因此它固定了版本,却没有固定版本背后的字节。这就是缺口所在。像 package==1.2.3 这样的一行,索引为该版本提供哪个文件,就由哪个文件来满足要求,除非有机制检查该文件的哈希。
哈希检查属于安装器的职责,而本书的示例并不运行安装器。pip 文档确立了这样的规则:一旦有一条要求项带有哈希,所有要求项都必须带哈希,并且要求项必须固定到 URL、路径或 ==(pip,安全安装)。uv 关于 pip compile 的页面指出,若要用 uv pip install 或 uv pip sync 检查运行时依赖,应使用 --require-hashes(uv,pip compile)。除这句话之外,本书不断言 uv 的其他行为。
固定与哈希承担不同的工作,本章将二者区分开来。== 固定的是版本,这是示例所检查的;哈希固定的是字节,这是文件目前尚未包含的。若设一条 CI 规则,使任何没有精确固定的行都导致失败,文件就能保持在这种状态;这条规则只是一项建议,本书并不运行它。
当某个固定项被有意更改时,这一更改应以 requirements 文件的已审查差异的形式出现,并在提交信息中写明原因。若构建自行改写该文件,固定项就会在无人阅读的情况下变动,这与自动重新生成工具固定项的流水线是同一种失败。
固定表明某个定义、模型文件或要求项自审查以来没有变化,哈希表明某个文件没有变化。二者都不能表明该对象是安全的。行为检查、格式规则和审查各自在本章所述的限度内缩小这一风险,而本章的示例展示了每一种手段在何处止步。
**工作准则:**用 == 固定每一条要求项,并为每一行记录哈希,使安装在任何字节发生变化时都会失败。在哈希就位之前,应当说明版本已被固定,而不要说字节已被固定。
本章,在本版次中
版次 2026.11.3示例于 2026年11月22日 通过5 of 5个示例 in this chapter pass
译自英文版图书,版次 2026.11.3。