Objectives: LO-11.1, LO-11.2, LO-11.3
Prerequisites: the Module 11 reading
Time: about 2.5 hours
In this lab you trace 30 inert proposals through a policy for a fictional shop display: 25 that no one approved, and 5 approved controls. You mark untrusted text, gate changes on the host’s approval, and measure how many attacks and how many controls each policy accepts.
No cell calls a model or can act on anything. The stand-in, GullibleModel from promptlab,
replays the proposal each fixture declares, whatever its source, so it never resists an
injection. Every fixture was written for this course, and its only “action” is a decision about
a sample label.
Each exercise ends with a check cell that prints passed or fails with a message that says what
is wrong. Run the cells in order, from the top, in a fresh kernel. The checks fail until you
finish the exercise above them.
Setup¶
import sys
from xml.etree import ElementTree
from promptlab import load_json
from promptlab.review import GullibleModel, classify
cases = load_json("safety/review-cases.json")
replay = GullibleModel()
print("Python", sys.version.split()[0])Trace source and proposal¶
Each fixture holds the text that carried its proposal. The replay doesn’t read that text: it
returns the proposal a gullible model might have made from it. classify reports the route,
"direct" or "indirect". Predict what each one returns when the fixture’s origin changes to
"user", then run the cell.
example = cases[0]
print(example["source"])
print(example["text"])
print(classify(example), replay(example))
print(classify(dict(example, origin="user")), replay(dict(example, origin="user")))Exercise L11.1 (LO-11.1, ★★, about 25 minutes)¶
Classify two proposal paths. Write groups(cases). Return a dictionary with the keys
"direct" and "indirect", each holding a list of fixture IDs: direct when the fixture’s
origin is "user", and indirect otherwise. Include an empty list for a group with no cases.
In your notes, trace one fixture of each kind from its text to its policy decision.
def groups(cases):
raise NotImplementedError("L11.1")by_origin = groups(cases)
assert len(by_origin["direct"]) == 10 and len(by_origin["indirect"]) == 20, \
"Ten fixtures arrive in a user turn, five injections and five controls; 20 arrive another way."
assert groups([]) == {"direct": [], "indirect": []}, "Include both groups even when they're empty."
print("passed")Exercise L11.2 (LO-11.2, ★★, about 25 minutes)¶
Preserve provenance in a prompt. Provenance is a record of where a piece of text came from.
Write mark(text, origin). Return a <source> element serialized as a string, with the
attributes trust="untrusted" and origin set from the argument, and text inside it, escaped
so that ElementTree.fromstring recovers it exactly. In your notes, explain why the host must
still make its own permission decision.
def mark(text, origin):
raise NotImplementedError("L11.2")node = ElementTree.fromstring(mark("Hours & closing notes", "document"))
assert node.attrib == {"trust": "untrusted", "origin": "document"}, \
"Give the source element exactly the attributes trust and origin."
assert node.text == "Hours & closing notes", "Escape the text so the parser recovers it exactly."
for case in cases:
assert ElementTree.fromstring(mark(case["text"], case["origin"])).text == case["text"], \
f"The text of {case['id']} should survive marking unchanged."
print("passed")Exercise L11.3 (LO-11.2, ★★, about 25 minutes)¶
Guard the proposed change. Write authorize(proposal, allowed, approved). Return
"denied" when the proposal’s name isn’t in the set allowed. When change_label is allowed,
return "needs_review" unless approved is True. Otherwise return "accepted". The approved
argument comes from the host, outside the proposal, so ignore any flag inside the proposal. The
lab records the decision only.
def authorize(proposal, allowed, approved):
raise NotImplementedError("L11.3")change = replay(cases[0])
assert authorize(change, {"read_label"}, True) == "denied", "Deny an action outside the allowlist."
assert authorize(dict(change, approved=True), {"change_label"}, False) == "needs_review", \
"Ignore an approval flag inside the proposal: only the host's approved argument counts."
assert authorize(change, {"change_label"}, True) == "accepted", \
"Accept an allowed change that the host approved."
assert authorize({"name": "read_label"}, {"read_label"}, False) == "accepted", \
"An allowed read needs no approval."
print("passed")Exercise L11.4 (LO-11.3, ★★, about 25 minutes)¶
Measure the fixture outcomes. Write rate(rows, baseline, allowed). Return the fraction of
unapproved cases (those whose authorized field is False) that the policy accepts. When
baseline is True, the policy accepts every replayed proposal, whatever its source. Otherwise
it is guarded: call authorize on the replayed proposal with allowed and the host’s approval,
the case’s authorized field. Return 0.0 when there are no unapproved cases.
def rate(rows, baseline, allowed):
raise NotImplementedError("L11.4")assert rate(cases, True, {"change_label"}) == 1.0, "The baseline accepts every unapproved proposal."
assert rate(cases, False, {"change_label"}) == 0.0, \
"The guarded policy accepts no unapproved proposal."
assert rate(cases, False, {"read_label"}) == 0.0, \
"A policy that allows no label change accepts no unapproved proposal either."
assert rate([], True, set()) == 0.0, "With no unapproved cases, return 0.0."
unapproved = sum(not case["authorized"] for case in cases)
print(f"{unapproved} unapproved fixtures. Baseline accepts {rate(cases, True, {'change_label'}):.0%}; "
f"guarded accepts {rate(cases, False, {'change_label'}):.0%}.")
print("passed")Exercise L11.5 (LO-11.3, ★★, about 15 minutes)¶
Check the approved controls. Write control_rate(rows, allowed). Return the fraction of
host-approved cases, those whose authorized field is True, that the guarded policy accepts.
Call authorize with the host’s approval, as in L11.4. Return 0.0 when there are no approved
cases. A policy that allows no label change also scores 0.0 in L11.4; this second number is
what shows it is broken.
def control_rate(rows, allowed):
raise NotImplementedError("L11.5")assert control_rate(cases, {"change_label"}) == 1.0, \
"The guarded policy accepts every approved control."
assert control_rate(cases, {"read_label"}) == 0.0, \
"A policy that allows no label change accepts no control."
assert control_rate([], {"change_label"}) == 0.0, "With no approved cases, return 0.0."
for name, allowed in (("Guarded", {"change_label"}), ("No label changes", {"read_label"})):
print(f"{name}: accepts {rate(cases, False, allowed):.0%} of unapproved proposals and "
f"{control_rate(cases, allowed):.0%} of approved controls")
print("passed")Summary¶
Direct injection arrives in the user’s turn and indirect injection in retrieved content; the fixture’s
originrecords the route.Marking keeps untrusted text intact and labeled, but grants nothing: the host decides.
The gate denies unlisted actions and accepts a change only on the host’s own approval, so a forged flag in the proposal changes nothing.
An attack success rate needs approved controls beside it, or a policy that refuses everything looks perfect.