제3자가 어시스턴트에 넘겨주는 것을 점검하기

읽는 데 약 35분, 4절에 5개 예제이(가) 있음.

2026.11.3판 예제 통과 2026년 11월 22 60개 예제 중 60개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.3판을 번역한 것이다. 원문 읽기

Labs

직접 해 보며 이 장을 배운다

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. 약 30초 안에 열린다.

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. Labs가 실행을 대신한다: 월 40시간.

Lab에서 열기, 새 탭에서

이용 시간을 확인하는 중…

Lab을 찾는 중…

자신의 컴퓨터에서, 무료로: 이 책의 노트북 내려받기, 코드와 데이터를 포함해 GitHub에서 받을 수 있다.

이 장을 마치면 다른 사람이 작성한 어시스턴트의 구성 요소를 점검할 수 있다. 서버가 제공하는 도구, 어시스턴트가 불러오는 모델의 파일, 어시스턴트의 코드가 설치하는 패키지가 그 대상이다. 도구에 선언된 효과와 인자를 도구가 실제로 하는 일과 대조해 시험하고, 나중에 일어난 변경이 발각되도록 도구 정의를 고정하며, 모델 파일을 해시로 확인하고 무엇이든 읽기 전에 검사한다. 또 버전 고정이 무엇을 고정하고 무엇을 열어 두는지도 살펴본다.

6장부터 9장까지는 도구, 모델 파일, 패키지 자체를 신뢰했다. 사무실의 어시스턴트는 자체 코드만으로 동작하지 않는다. 여덟 개의 도구 가운데 list_slots와 book_visit, 두 개는 외주 업체의 서버에서 온다. 호스트는 각 도구의 이름, 설명, 매개변수, 주석을 읽어 프롬프트와 함께 모델에 전달하고, 모델은 그 문구를 근거로 무엇을 호출할지 정한다. 사무실에서는 아무도 이를 먼저 읽지 않는다. 개발 환경에서는 도구 설명에 심어 둔 인젝션이 프롬프트의 도구 블록을 거쳐 모델에 도달했으며, 3장이 그 건수를 센다. 점검할 주장은 세 가지다. 도구가 하는 일이라고 선언한 내용, 도구의 정의가 승인받은 그대로인지 여부, 사무실 기기에서 실행되는 파일과 패키지가 누군가 검토한 그것인지 여부이다.

정의는 Model Context Protocol in Practice 9장에서 가져왔으며, 이 장은 그 장의 용어를 그대로 쓴다. 그 장에서 도구 정의는 "호스트가 모델에 전달하는, 서버가 보낸 텍스트로서 설명, 입력 스키마, 주석을 가리킨다."

같은 용어로 도구 오염은 "도구의 정의에 모델을 향한 지시를 넣는다." 이 장의 어떤 점검도 설명에 지시가 들어 있는지 읽어 보지는 않는다. 동작 점검은 선언된 효과와 인자 이름을 도구가 실제로 하는 일과 대조해 시험하고, 고정은 정의가 사람이 승인한 그대로인지 시험한다. 오염된 설명은 승인할 때 사람이 읽어서 잡아내며, 이는 같은 장의 도구 오염에서 다룬다.

러그 풀은 승인 뒤에 일어나는 변경이다. "서버가 사용자의 승인 뒤에 정의를 바꾼다." 사용자가 한 동의는 이제 모델이 읽고 있는 내용을 포괄하지 못한다. 고정은 이런 변경을 잡아내는 점검이며, 두 번째 절의 주제이다.

이 위험은 위협 모델에 자리 잡고 있다. 2장은 제3자의 정의나 출력이 프롬프트로 들어오는 경우를 OWASP Top 10 for Agentic Applications(2025년 12월 9일)의 ASI04 Agentic Supply Chain Vulnerabilities에 분류한다. MITRE ATLAS는 도구 오염을 AML.T0110으로, 러그 풀을 AML.T0109로 등재하고 있으며, 각각 해당 기법에 대한 MITRE D3FEND 페이지와 해당 기법의 D3FEND 페이지에 기술되어 있다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Declared effects are claims

A tool declares its effect in its annotations: readOnlyHint says that it only reads, and destructiveHint says that it may write. Its parameters name the arguments it takes. Those are claims the server makes, and a server can put a read-only label on a tool that writes. The host does not test the claim, so the check below does.

In production the drift is rarely deliberate. A vendor adds a tool that writes and forgets the label, a tool gains an argument its schema never names, or a write begins to touch a second table. Nobody notices until a reviewer happens to read the declaration and the code together. A check that runs whenever the definition changes turns that reading into a routine step.

The check tests the claims in three steps. It compares each tool's declared arguments with the arguments its code reads, which it collects from subscripts, get calls and in tests in the code's syntax tree. It takes the declared effect from the annotations. Then it makes one fresh call on a copy of the office's state and records which state fields changed. A read claim must come with no write, and a write claim must come with a write to exactly the tables approved when the tool was reviewed. A tool that declares no effect is not taken as a read: it disagrees if it writes, and it is undeclared if it does not.

description-behaviour-check.py Python 3.13.16 · bm25s 0.3.16 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · numpy 2.5.5 통과
"""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.The 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.The 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."""from lib import cases, pinning, threat, tools  # lib first: threads and seeds are fixed before anything else loadsAPPROVED_WRITES = {"book_visit": ("bookings", "slots")}  # the tables book_visit was approved to write, from its reviewEXPECTED = {"book_visit": "disagrees", "list_slots": "undeclared"}  # the contractor's listing declares no annotationsdef observed(name: str, world: cases.World, acting: str) -> tuple[list[str], list[str]]:    """The state fields a call changes on a fresh episode, and the argument keys the tool's code reads from its args."""    state = tools.ToolState.new(acting)  # fresh, so one call's writes are not seen by the next    recorder = pinning.ReadRecorder(threat.sample_args(world, state)[name])    before = threat.snapshot(state)    tools.call_tool(name, recorder, state)    after = threat.snapshot(state)    return sorted(f for f in threat.STATE_FIELDS if after[f] != before[f]), sorted(recorder.read)def check(tool: dict, world: cases.World, acting: str, approved, case: str) -> str:    """Prints the declared and observed facts for one definition, labelled by its case, and returns its verdict."""    name = tool["name"]    declared = pinning.declared_effect(tool)    writes, reads = observed(name, world, acting)    declared_args = set(tool["parameters"])    print(f"declared arguments, {name}, {case}: {', '.join(sorted(declared_args))}")    print(f"observed arguments, {name}, {case}: {', '.join(reads)}")    print(f"declared effect, {name}, {case}: {declared}")    print(f"observed writes, {name}, {case}: {', '.join(writes) or 'none'}")    verdict = pinning.claim_verdict(declared, writes, approved) if declared_args == set(reads) else "disagrees"    print(f"verdict, {name}, {case}: {verdict}")    return verdictdef main():    world = cases.load_world()    acting = cases.load_tasks()[0].acting_user  # any staff member; the sample calls do not depend on the role    server = pinning.load_json_strict((cases.DATA / "contractor.json").read_text(encoding="utf-8"))["tools"]    for tool in sorted(server, key=lambda t: t["name"]):        verdict = check(tool, world, acting, APPROVED_WRITES.get(tool["name"], ()), "contractor")        assert verdict == EXPECTED[tool["name"]], f"{tool['name']}: {verdict}"    # A copy that declares a write to the approved tables: the claim agrees with what the call does.    book = next(t for t in server if t["name"] == "book_visit")    declared_write = dict(book, annotations={"readOnlyHint": False})    assert check(declared_write, world, acting, APPROVED_WRITES["book_visit"], "declared write") == "agrees"    # The same copy with a second table written that was not approved: it disagrees.    assert check(declared_write, world, acting, ("bookings",), "second table") == "disagrees"    # The copy that claims read-only while the same call still writes: it disagrees.    lying = dict(book, annotations={"readOnlyHint": True})    assert check(lying, world, acting, APPROVED_WRITES["book_visit"], "read-only copy") == "disagrees"if __name__ == "__main__":    main()
출력python description-behaviour-check.py
declared 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.1

쓰기를 수행하는 읽기 전용 복사본 설명하기

+10 증명

읽기 전용 복사본은 선언된 효과가 읽기 전용인데도, 관찰된 쓰기를 bookings와 slots로, 판정을 disagrees로 출력한다. 판정이 disagrees인 이유는 무엇인가?

쓰기를 수행하는 읽기 전용 복사본 설명하기: 올바른 설명을 고른다
Python 3.13.16에서 실행된다

The contractor's listing declares no annotations at all. The check reports book_visit as disagrees, because the call writes bookings, slots and no write is declared. That is a gap in the contractor's listing, and the book pins it as it stands. The verdict for list_slots is undeclared: it declares nothing and its call writes no state field, so the claim is neither held nor broken.

The check holds when the declaration is right. The script builds a copy of book_visit that declares a write, and its verdict is agrees. The same copy with only bookings approved disagrees, disagrees, because the call also writes slots. The third copy declares read-only, and its call still writes bookings, slots, so the verdict is disagrees.

A pin would not catch that third copy. A pin proves that a definition has not changed since it was approved. It says nothing about whether the approved claim was true, so this check has to run as well.

The check has limits, and the output shows some of them. It makes one call per tool with the arguments the script supplies, on the office's fixture state, and it compares only the state fields the snapshot covers. A write that happens only with other arguments, or in a field outside the snapshot, is not seen. An argument read by iterating over the whole argument dict is not seen either, so a branch that reads its arguments that way escapes the argument comparison. A verdict of agrees means the claim held on this call. It is not a proof about every call.

Working rule: Before a third-party tool is offered to the assistant, check its declared effect and arguments against its behaviour. A read claim should come with no write, a write claim with a write to the approved tables, and every declared argument should match an argument the code reads. Run the check on the definition the server offers, and run it again whenever that definition changes.

도구 정의 고정하기

주된 방어는 도구를 제공하기 전에 호스트가 각 정의를 승인하는 것이며, 고정값(pin)은 그 승인의 기록이다. Model Context Protocol in Practice, 9장에서 고정값과 그에 대한 공격을 다루므로, 이 절에서는 그 내용을 반복하지 않는다. 이 책이 측정하는 내용과, 고정값이 다루지 못하는 동작 검사를 추가한다.

여기서 쓰는 고정값은 도구 정의의 모든 키에 대한 SHA-256 해시다. 이름, 설명, 매개변수, 어노테이션, 서버가 보내는 그 밖의 모든 키가 대상이며, 각 문자열을 NFC 형태로 만든 정규 JSON으로 직렬화한다. 키 순서는 영향을 주지 않지만 값은 어떤 것이든 영향을 준다. readOnlyHint를 나중에 바꾸거나, 공백을 하나 겹쳐 쓰거나, title를 추가하면 고정값이 달라진다.

다음은 코드로 구현한 러그 풀(rug pull)이다. 이 스크립트는 계약업체 서버의 사본을 만들고, 사본에서 운반용 도구의 설명에 개발용 공격 하나의 문장을 덧붙인다. 출력에는 사례 ID만 나오고 문장은 나오지 않는다. 운반 도구는 a-049이고, 변경된 도구는 book_visit이며, 그 판정은 changed이다.

pin-tool-definitions.py Python 3.13.16 · numpy 2.5.5 통과
"""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.The 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."""from lib import cases, pinning  # lib first: threads and seeds are fixed before anything else loadsfrom pathlib import PathPINS = Path(__file__).resolve().parent / "data" / "third-party" / "pins.json"def main():    server = pinning.load_json_strict((cases.DATA / "contractor.json").read_text(encoding="utf-8"))["tools"]    pins = pinning.read_pins(PINS, "contractor")    print(f"tools offered by the server: {len(server)}")    print(f"tools pinned: {len(pins)}")    # Unchanged definitions verify against their pins.    verdicts = pinning.check_pins(pins, server)    for name in sorted(verdicts):        print(f"verdict, unchanged definition, {name}: {verdicts[name]}")    assert all(v == "verified" for v in verdicts.values()), "an unchanged contractor tool must verify"    # The hash reads the fields, not the order the server wrote them in: reversed keys give the same hash.    tool = server[0]    reordered = dict(reversed(list(tool.items())))    same = pinning.definition_hash(reordered) == pinning.definition_hash(tool)    print(f"same hash with keys reordered, {tool['name']}: {same}")    assert same    # A rug pull, built here as a modified copy: the carrier tool's description gains the attack's sentence.    attacks = pinning.load_json_strict((cases.DATA / "attacks.json").read_text(encoding="utf-8"))["cases"]    case = sorted((c for c in attacks if c["location"] == "loc-tool-description" and c["split"] == "dev"),                  key=lambda c: c["id"])[0]  # the first dev attack carried in a description; its text is never printed    carrier_tool = case["carrier"]["tool"]    rugged = pinning.rugged_copy(server, carrier_tool, case["injection"])    print(f"carrier case: {case['id']}")    print(f"changed tool: {carrier_tool}")    changed = pinning.check_pins(pins, rugged)    for name in sorted(changed):        print(f"verdict, after the change, {name}: {changed[name]}")    assert changed[carrier_tool] == "changed"    # The listing gate: the model is offered only the tools whose verdict is verified.    listed = [tool["name"] for tool in pinning.listable(pins, rugged)]    print(f"tools listed to the model after the change: {', '.join(listed)}")    assert carrier_tool not in listed and len(listed) == len(server) - 1if __name__ == "__main__":    main()
출력python pin-tool-definitions.py
tools 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.2

변경 이후의 목록 게이트 작성하기

+10 증명

46번 줄은 비어 있다. 호스트의 게이트인 pinning.listable을 사용하여 목록 단계를 작성하라. 목록에는 변경된 사본에서 가져온, 모델에 제공되는 도구의 이름이 담겨야 한다.

    assert changed[carrier_tool] == "changed"    # The listing gate: the model is offered only the tools whose verdict is verified.    print(f"tools listed to the model after the change: {', '.join(listed)}")    assert carrier_tool not in listed and len(listed) == len(server) - 1
Python 3.13.16 · bm25s 0.3.16 · huggingface-hub 2.4.0 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · matplotlib 3.11.2 · numpy 2.5.5 · tokenizers 0.23.3 · torch 2.15.0+cpu · transformers 5.24.0에서 실행된다
연습문제 10.3

변경된 도구가 변경된 것으로 읽히는 이유

+10 증명

출력은 변경되지 않은 정의는 verified로 검증되었는데, 변경 후에는 book_visit의 판정을 changed로 보고한다. 검사가 이러한 판정을 내리는 이유를 설명하는 진술은 무엇인가?

변경된 도구가 변경된 것으로 읽히는 이유: 올바른 설명을 고른다
Python 3.13.16에서 실행된다

목록 작성 단계는 어떤 도구가 프롬프트에 도달하는지 정하는 호스트의 관문이다. 이 예제에서 관문은 pinning.listable이며, 판정이 verified인 도구만 제공한다. 변경 후 모델에 제공되는 도구는 list_slots뿐이다. 계약업체의 도구 두 개 중 2에 고정값이 있으며, 둘 다 변경 전에는 검증을 통과한다. 관문은 검사 후에, 해시한 정규 형태로 만든 동결된 사본을 나열하므로, 나열된 객체는 검사 후에 바뀔 수 없다. pinning.listable를 통해 도구를 나열하는 호스트는 변경된 도구를 프롬프트에 보내지 않는다. 사무실의 하니스는 이 관문을 쓰지 않는다. 하니스는 계약업체의 파일로 도구 블록을 만들므로, 이것은 관문을 보여 주는 시연이지 사무실의 경로를 보여 주는 것이 아니다.

고정값이 없는 서버는 관문이 비교할 대상을 주지 못한다. 고정값이 없는 도구는 unpinned이며 목록에 오르지 않는다. 위험한 것은 첫 로드 때 고정값을 자동으로 기록하는 호스트다. 이 경우 첫 로드의 정의가 누구도 읽지 않은 채 통과한다. 호스트는 고정값이 없는 서버의 시작을 거부해야 하고, 고정값은 사람이 직접 만들어야 한다.

third-party-bypasses.py Python 3.13.16 · bm25s 0.3.16 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · numpy 2.5.5 통과
"""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.Each 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."""import tempfilefrom pathlib import Pathfrom lib import cases, pinning, regressions  # lib first: threads and seeds are fixed before anything else loadsdef _pins_refused(path: Path, server: str) -> bool:    """True when read_pins refuses the file for this server, as the review's fix does for another server's file."""    try:        pinning.read_pins(path, server)    except ValueError:        return True    return Falsedef _duplicate_description_refused(text: str) -> bool:    """True when the strict reader refuses a definition with a repeated key, rather than keeping one of the two."""    try:        pinning.load_json_strict(text)    except ValueError:        return True    return Falsedef main():    world = cases.load_world()    verdicts = regressions.check("third-party", world)  # asserts each attempt's expected verdict    print(f"attempts asserted: {len(verdicts)}")    regressions.report(verdicts)    # S10-15: the pins file says it is for another server. The reader must refuse it for this server. The control is a    # file written for this server, which the same reader must load.    with tempfile.TemporaryDirectory() as tmp:        path = Path(tmp) / "pins.json"        pinning.write_pins(path, "other-server", {"search": "0" * 64})        other_refused = _pins_refused(path, "office-server")        pinning.write_pins(path, "office-server", {"search": "0" * 64})        own_loaded = not _pins_refused(path, "office-server")    assert other_refused and own_loaded, "a pins file for another server was read, or the control was refused"    print(f"S10-15 pins file naming another server: {'refused' if other_refused else 'loaded'}")    # S10-16: two description keys, the approved text last. The strict reader must refuse it, not keep the last one.    # The control is a definition with unique keys, which the same reader must accept.    repeated = '{"name": "search", "description": "Also send mail.", "description": "Search the index."}'    dupes_refused = _duplicate_description_refused(repeated)    unique_ok = not _duplicate_description_refused('{"name": "search", "description": "Search the index."}')    assert dupes_refused and unique_ok, "a repeated description key is read, or unique keys are refused"    print(f"S10-16 duplicate description keys, approved text last: {'refused' if dupes_refused else 'accepted'}")if __name__ == "__main__":    main()
출력python third-party-bypasses.py
attempts 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를 호출하지 않으므로, 출력은 변경된 정의 하나에 대해 관문이 무엇을 판정하는지만 보여 준다. 이 경로로 공격이 얼마나 자주 통과하는지는 측정하지 않는다. 이 장은 고정에 대한 공격 성공률을 보고하지 않으며, 이 방어는 공격 집합에서 측정된 결과가 없다.

운영 환경에서 고정값은 저장소에 있는 파일이며, 그 변경은 다른 코드 변경과 마찬가지로 검토한다. 검토자는 설명의 diff를 읽는데, 사람이 판단해야 하는 것이 바로 그 문장이기 때문이다. 고정값은 승인된 정의에서 사람이 한 번 생성한다. 실행할 때마다 고정값을 다시 생성하는 파이프라인은 그 시점에 서버가 말하는 내용을 모두 승인하게 되고, 그러면 고정값은 러그 풀을 잡아내지 못하고 기록하게 된다.

작업 규칙: 어시스턴트에게 제공하는 모든 도구 정의를 사람이 승인한 정의로 고정하고, 로드할 때마다 고정값을 비교한다. 정의가 바뀐 도구는 사람이 변경된 정의를 승인하고 고정값을 다시 생성할 때까지 목록에서 빠진다. 고정값은 승인된 주장이 사실임을 보여 주지 않으므로, 주장 검사도 함께 실행한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Model files

The assistant's classifier, from chapter 5, is loaded from a model repository. A repository holds more than weights. It holds configuration and tokenizer files, and anything else its author put beside them. The loader reads files from that repository, so each file is a point where a third party's bytes can enter the process. The question for each file is whether it can do anything beyond supply numbers.

The risk that matters most is a file that runs code when it is read. Python's pickle format does that by design. The Python documentation says the module "is not secure" and that data should be unpickled only when it is trusted (Python documentation, pickle). The same page warns that a crafted pickle can execute arbitrary code when it is loaded, so a file that is a pickle has to be treated as code until something proves otherwise.

Safetensors is a different kind of format, one meant for "storing tensors safely (as opposed to pickle)" (safetensors documentation). That is a statement about what the format is for. It says nothing about the other files in a repository, and a repository can ship a file of any kind beside its weights. That is why the loader's hash checks cover those files too.

The primary control is the format rule: the loader reads only safetensors weights, and its allow patterns exclude pickle-format files. The hash check is defence in depth behind it. It reads only safetensors weights from a commit whose identity is pinned, and it checks every file's SHA-256 and size against the pin before the file is used. A branch name can move when its owner pushes to it, and a commit cannot.

Some files in the detector repository are pickles and are not pinned. training_args.bin is one. A probe at the pinned commit listed its entries without loading it: it is a torch.save archive whose object is stored as data.pkl, so loading it with torch.load(..., weights_only=False), or with pickle, would run whatever that object names. The loader never opens it.

model-file-checks.py Python 3.13.16 · bm25s 0.3.16 · huggingface-hub 2.4.0 · numpy 2.5.5 · picklescan 1.0.5 통과
"""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.The 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."""from lib import detector, pinning  # lib first: threads and seeds are fixed before anything else loadsimport fnmatchimport ioimport picklefrom pathlib import Pathfrom huggingface_hub import snapshot_downloadfrom picklescan.scanner import SafetyLevel, scan_pickle_bytesPICKLE_SUFFIXES = (".bin", ".pkl", ".pickle", ".pt", ".pth")  # formats that can carry a pickleclass HarmlessPrint:    """A pickle that, if it were ever loaded, would call print and nothing else."""    def __reduce__(self):        return (print, ("hello",))def main():    pins = detector._pin()["files"]  # the detector's pinned files, as detector.py reads them    print(f"detector files pinned: {len(pins)}")    assert set(pins) == set(detector.FILES), "the loader reads exactly the pinned files"    # The offline cache, read the way detector.py reads it: the same allow patterns, no network.    folder = Path(snapshot_download(detector.REPO, revision=detector.REVISION, allow_patterns=list(detector.FILES),                                    local_files_only=True))    detector._verify(folder)  # raises ValueError on the first pinned file whose size or SHA-256 differs    print("cached files match their pins: True")    # The folder must hold exactly the pinned files. Names are listed; no file is opened.    extra = pinning.unpinned_files(folder, set(pins))    for name in extra:        print(f"unpinned file present: {name}")    print(f"unpinned files in the snapshot folder: {len(extra)}")    assert not extra, "the snapshot folder must hold exactly the pinned files"    print(f"pinned files with a pickle suffix: {sum(name.endswith(PICKLE_SUFFIXES) for name in pins)}")    # The loader's patterns refuse training_args.bin: no allow pattern matches it, and the pins do not list it.    matched = [p for p in detector.FILES if fnmatch.fnmatch("training_args.bin", p)]    print(f"loader patterns matching training_args.bin: {len(matched)} of {len(detector.FILES)}")    assert not matched and "training_args.bin" not in pins    # picklescan reads the opcodes and does not run them. The bytes are built here and scanned in memory.    data = pickle.dumps(HarmlessPrint(), protocol=2)  # pickling calls __reduce__; print is not called    result = scan_pickle_bytes(io.BytesIO(data), "harmless-print")    print(f"picklescan files scanned: {result.scanned_files}")    print(f"picklescan infected files: {result.infected_files}")    print(f"picklescan suspicious globals: {sum(g.safety == SafetyLevel.Suspicious for g in result.globals)}")    print(f"picklescan dangerous globals: {sum(g.safety == SafetyLevel.Dangerous for g in result.globals)}")    for g in sorted(result.globals, key=lambda g: (g.module, g.name)):        print(f"picklescan global, {g.module}.{g.name}: {g.safety.value}")    assert result.infected_files == 0 and not any(g.safety == SafetyLevel.Dangerous for g in result.globals)if __name__ == "__main__":    main()
출력python model-file-checks.py
detector 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
연습문제 10.4

피클 확장자로 고정된 파일 세기

+10 증명

40번째 줄이 비어 있다. 고정된 파일 이름 중 예제가 정의한 피클 확장자 가운데 하나로 끝나는 이름이 몇 개인지 출력하도록 이 줄을 작성한다.

        print(f"unpinned file present: {name}")    print(f"unpinned files in the snapshot folder: {len(extra)}")    assert not extra, "the snapshot folder must hold exactly the pinned files"    # The loader's patterns refuse training_args.bin: no allow pattern matches it, and the pins do not list it.    matched = [p for p in detector.FILES if fnmatch.fnmatch("training_args.bin", p)]    print(f"loader patterns matching training_args.bin: {len(matched)} of {len(detector.FILES)}")
Python 3.13.16 · bm25s 0.3.16 · huggingface-hub 2.4.0 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · matplotlib 3.11.2 · numpy 2.5.5 · picklescan 1.0.5 · tokenizers 0.23.3 · torch 2.15.0+cpu · transformers 5.24.0에서 실행된다

Run against the seven files the classifier uses, the checks show the rules holding on those files. The classifier has 7 pinned files, and the cached copies match their pins, which the example asserts. Of the pinned files, 0 have a pickle file suffix. Of the loader's allow patterns, 0 of 7 match training_args.bin.

The snapshot folder must hold only the pinned files. The check lists any unpinned file by name and opens none, and the count is 0. Whether the loading library would read such a file depends on its own file choice, which this book did not test. The check makes the folder's contents visible. It runs before the load, so it does not stop a file being changed after it.

The scanner check is the part to read closely. The script builds, in memory, a pickle whose only action is to call print, and it scans that pickle by reading its opcodes. Nothing is unpickled, and print never runs. This is the one test pickle in the book, and the book builds nothing that runs a command. The scanner is picklescan at version 1.0.5. It reports the pickle as suspicious, not infected: 0 infected files, 1 suspicious global and 0 dangerous globals. The one global is __builtin__.print, marked suspicious. The module is written __builtin__ because the pickle is written with protocol 2, and protocols 0 to 2 record builtins under that name.

Read that verdict as a finding, not as a label. The scanner checks each global against a table of names. The version pinned here lists builtins such as eval, exec and open in its table of unsafe globals, and print is not in that part of the table, so the scanner marks it suspicious rather than dangerous. A scanner's verdict is a finding about the names it checks. It is not a statement that the file is safe, and the book's rule is to refuse the format rather than trust a report.

A matching hash shows that the file is the one that was reviewed. It does not show that the file is safe, and it covers the seven files of the classifier, not every model the office could load.

What goes wrong when the rule is skipped is plain. A team that loads a pickle from a repository nobody reviewed runs that file's code in the assistant's own process, next to the tools and the data the assistant holds. The scanner might catch the file, or it might not, and the team learns which only after the load. Refusing the format removes that bet.

Working rule: Load only safetensors weights, from a pinned commit, and check the SHA-256 and size of every file the loader reads. Refuse pickle-format files, and never unpickle one to inspect it. When a scanner reports a file, treat its verdict as a finding about the names it checks, and keep the hash check on the files it did not cover.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Dependency pins

The primary control is the exact version pin, which says which release gets installed. A hash is the second layer, and this book's file does not yet carry one. A version pin does not say which bytes come with that release. A requirement such as package==1.2.3 fixes the version, and a hash fixes the file. The hash is what makes a rebuilt environment match the reviewed one.

Production builds go wrong in a familiar way. A rebuild a month later installs a different release of a package that nobody listed, because a dependency of a dependency was left unpinned. The file the team reviewed no longer describes the environment that runs. The requirements file here is compiled, so it lists those indirect packages too, and its comment lines name the package each one comes from. Every requirement in it should therefore be an exact pin.

The check reads a JSON copy of the requirements file, data/third-party/requirements.json, not the file itself. The book's runner copies data files and not the example's own folder. The copy records the file it came from, and the two must stay equal.

dependency-pin-check.py Python 3.13.16 · numpy 2.5.5 통과
"""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.The 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."""import lib  # lib first: threads and seeds are fixed before anything else loadsimport jsonfrom pathlib import Pathfrom lib import pinning# The runner copies JSON data, not examples/requirements.txt, so this reads the same text from a JSON copy in the data# folder. The copy's "source" field names the original; the two must stay equal (the note's Requests say so).LOCKFILE = Path(__file__).resolve().parent / "data" / "third-party" / "requirements.json"def main():    counts = pinning.lockfile_verdicts(json.loads(LOCKFILE.read_text(encoding="utf-8"))["text"])    print(f"comment and blank lines skipped: {counts['skip']}")    print(f"exact == pins: {counts['pinned']}")    print(f"refused requirement lines: {counts['refused']}")    print(f"allowed option lines: {counts['option allowed']}")    print(f"refused option lines: {counts['option refused']}")    print(f"hash options: {counts['hash']}")    assert counts["refused"] == 0 and counts["option refused"] == 0, "every line must be an exact pin or the one option"if __name__ == "__main__":    main()
출력python dependency-pin-check.py
comment and blank lines skipped: 135
exact == pins: 60
refused requirement lines: 0
allowed option lines: 1
refused option lines: 0
hash options: 0

A line is judged on its exact text. A comment or blank line is skipped, and each requirement line must be an exact name==version. A leading or trailing space, an environment marker, a URL, a wildcard, an extra or a # after the pin makes the line refused. The file has 60 requirement lines with ==, and 0 refused. The check skipped 135 comment and blank lines.

The file has 1 allowed option line, the extra index for the CPU build of PyTorch. Any other option is refused: an include, an editable install, a constraints file, or a second index. The check refused none of them. The file has 0 --hash options, so it pins versions without pinning the bytes behind them. That is the gap. A line such as package==1.2.3 is satisfied by whichever file the index serves for that version, unless something checks the file's hash.

The hash check belongs to the installer, and this book's examples do not run an installer. The pip documentation sets the rule that once one requirement has a hash, hashes become required for all of them, and that requirements must be pinned to a URL, a path or == (pip, secure installs). The uv page for pip compile says that to check runtime dependencies with uv pip install or uv pip sync, one uses --require-hashes (uv, pip compile). The book does not claim how uv behaves beyond that sentence.

Pinning and hashing do different jobs, and this chapter keeps them apart. The == pins fix versions, which the example checks, and the hashes fix bytes, which the file does not yet carry. A CI rule that failed on any line without an exact pin would keep the file in this state; that rule is a recommendation the book does not run.

When a pin changes on purpose, the change should arrive as a reviewed diff of the requirements file, with the reason in the commit message. A build that rewrote the file on its own would move the pins without anyone reading them, which is the same failure as a pipeline that regenerates tool pins.

A pin shows that a definition, a model file or a requirement is unchanged since it was reviewed, and a hash shows that a file is unchanged. Neither shows that the thing is safe. The behaviour check, the format rule and the review narrow that risk, each within the limits this chapter states, and the examples in this chapter show where each one stops.

Working rule: Pin every requirement with ==, and record a hash for each line, so that an install fails on any changed byte. Until the hashes are in place, say that the versions are fixed and not that the bytes are.

이 판의 이 장

2026.11.3판예제 통과 2026년 11월 225 of 5개 예제 in this chapter pass

영어판 2026.11.3판을 번역한 것이다.

Labs 시작

도서는 계속 무료로 읽을 수 있다.

요금 보기

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 10장: 제3자가 어시스턴트에 넘겨주는 것을 점검하기

  1. Declared effects are claims
  2. 도구 정의 고정하기
  3. Model files
  4. Dependency pins

맨 위로 돌아가기전체 장