Indirect Prompt Injection

Michael BrenndoerferDecember 2, 202642 min read

Learn how indirect prompt injection affects read-only assistants. Separate access control from content marks and choose evidence views with a policy engine.

Language AI HandbookAll chapters
Part 61 of 67Agentic AI and Protocol Security
Chapter 466Indirect Prompt Injection
Reading the full chapter · 14 sections · 42 min14 sections · 42 min

All 14 sections · 42 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Indirect Prompt Injection

A library assistant can read a visitor guide to answer questions about the building. The guide often contains instructions for people. A sentence that explains how visitors pick up a map belongs in an answer about visiting, even if a content screen marks it as instruction-like. The same guide has no authority to change who may read a catalog record. If both decisions depend on the same marker, an ordinary guide can disappear from answers or be given influence it should never have had.

The preceding chapter traced the library assistant's read boundary. Here we make three decisions visible in a small policy exercise. We choose what evidence to include, make the access check from application state, and keep track of what a restrictive content policy costs on ordinary inputs.

Why indirect injection is structurally different

Prompt injection is a failure in which model input is interpreted as an instruction that changes application behavior outside the intended task. When the input reaches the model through material the application obtains on the user's behalf, it is commonly called indirect prompt injection. Examples of inbound data sources include retrieved reference material and tool results. Their source can be known and authenticated while their contents retain a data-only role. The UK's National Cyber Security Centre distinguishes this situation from controls that enforce a strict separation inside a conventional interpreter. NCSC prompt-injection analysis

A label that says “retrieved evidence” communicates the intended role of the data to the model. The application needs its own decisions about access and the next operation. Structured output limits what a downstream parser can accept. A schema-valid proposal can still be outside the caller's authority, so validate authorization separately in application code. OWASP Gen AI Security Project guidance

This distinction matters in a read-only assistant. An answer can be misleading even when the model has no write capability. A request for access can also be denied while a task succeeds with the remaining visible evidence. We will keep the example focused on those two outcomes: the usefulness of the returned evidence and the authority to retrieve or display it.

Which claim does a provenance label support?

Suppose a library maintains a collection of staff-approved policies. The ingestion record can say which edition a policy came from and whether it was in the reviewed collection. That is a provenance claim. It helps a maintainer decide what document to cite or replace when a newer edition appears. Neither the edition nor the review label states which software operations the answer model may request. A signed or otherwise authenticated source can be legitimate evidence and still contain ordinary instructions for its intended human audience.

This matters for how we design reviewer screens. A reviewer who sees Verified next to a document needs to know what was verified. It might refer to the document's identity, a checksum, a source system's authentication, or a human decision that the text matches a topic. The application needs to represent those judgments separately. If the reviewer chooses whether a location answer is sufficiently supported, a source identifier and version can be useful. The reviewer does not thereby grant the answer model new capabilities. The service's permission comes from the application policy.

A simple design exercise is to trace a document's origin through three representations. First there is the stored record in the catalog. Next there is the limited set of values selected for the model. Finally there is a proposal for what to show to the user. Where can a maintainer verify each representation's role? At retrieval the maintainer can verify which record and fields were read. At assembly the maintainer can check which fields were selected. At rendering the maintainer can verify the audience and assess how the proposal was accepted. Treat those as three different observations, even if one event store eventually records them.

Structured boundaries are useful chiefly when code enforces their semantics. A source wrapper can retain origin and mark fields through a pipeline. A receiving function can use the origin for logging or to select a view. A serializer can put a data record into a clearly named field. In each case the outside control depends on actual input types and routes. If the wrapper has a free-text field, a model may still process that field as language. Pair the wrapper with a separate enforcement point that understands which operations are legal for the request.

There is also a difference between factual relevance and authorization. Finding a guide that seems relevant to the user's location question cannot prove that the reader may see a particular copy. Permission may depend on which language or edition is available for the reader's collection. Use retrieval relevance to rank records that can participate under policy. State where authorization applies if resources are collected from multiple libraries. A design calling itself read-only still needs to check read rights for the requested resource and response audience.

The compound-system model we will build

Use the library's visitor guide and catalog location as familiar inputs. Each synthetic row has a source identifier, a display title, a room, and a preassigned screening mark. Think of the display title as a convenience field. The room is a typed fixture field the task needs. A separate truth label tells us which cases in this tiny exercise were intended to be flagged.

The application knows the current reader's permission separately from the row. An enum represents a screening result, and another enum represents a policy decision. The simulation consumes these values and returns a view of permitted fields. It does not call a model, classify raw text, connect to a service, or perform a tool action.

PythonIn [3]
CollapseExpand
from dataclasses import dataclass
from enum import Enum


class ContentMark(Enum):
    CLEAR = "clear"
    INSTRUCTION_LIKE = "instruction-like"
PythonIn [4]
CollapseExpand
class Strategy(Enum):
    REJECT_FLAGGED = "Reject marked"
    RESTRICT_FLAGGED = "Restrict marked"
    MINIMIZE_ALL = "Minimize all"


class Decision(Enum):
    DENY_ACCESS = "deny access"
    DROP_SOURCE = "drop source"
    ROOM_ONLY = "room only"
    ROOM_AND_TITLE = "room and title"
PythonIn [5]
CollapseExpand
@dataclass(frozen=True)
class Evidence:
    source_id: str
    title: str
    room: str
    mark: ContentMark


@dataclass(frozen=True)
class Fixture:
    evidence: Evidence
    review_expects_mark: bool

Define a small state space before writing policy

Imagine reviewing this implementation with a catalog maintainer. If policy treats the visitor guide as unusable in one branch, the maintainer needs to see whether the reason was access, source quality, or a content mark. A boolean flag called filtered would collapse those reasons and make the behavior hard to diagnose. Instead use a small set of decision values with an explicit interpretation. The set in this chapter distinguishes denial before content policy from dropping an authorized source after applying it. Both decisions can yield no view. Their category is useful when the result reaches the user or a maintainer.

Decide on what the record identifier means. We use an identifier for a whole fixture row. An actual retrieval system may work with one document and many fragments. In that design the permission check starts with the asset to which policy applies. If a fragment is independently authorized, the code needs the fragment's identifier. If access is defined per document, a trusted lookup has to map fragment to document before use. The state carried in the model request is not proof that the lookup happened.

Treat permissions as an argument to the policy function, separate from the retrieved evidence. The application can replace the permission set at the next evaluation without changing the record or its mark. The examples after the worked case will hold those other inputs fixed. With authentication or authorization distributed across service boundaries, whoever owns the permission decision needs a documented strategy for obtaining fresh enough state. The local function accepts the state supplied to it. It cannot tell whether a remote policy provider has recorded a more recent change.

Some applications require an answer to cite individual sources. That creates one more useful check. Ensure that the application records the origin of each selected field in a representation the caller may view. The source identifier in the fixture lets us trace the choice we made. In a real service there may be a distinct public citation identifier rather than the internal record key. Record where the conversion happens before a runtime begins copying sources into response text.

For the toy exercise, call a result useful if it still contains the room field needed by the original task. That definition leaves out several things readers care about, including accuracy, clarity and whether the guidance meets their needs. Keep the word useful anchored to this one criterion in the policy comparison. That will make it clear which conclusions transfer to another application and which require fresh evidence.

Marking instruction-like content

A mark is a cue for how cautiously to handle a record. In this exercise the cue is supplied by the fixture author. That lets us study what to do if it is right or wrong. A real signal can be calibrated against reviewed examples from the application. Deployed screening should be evaluated separately from the policy that consumes it. A good result from one layer gives no estimate of another layer's behavior.

The fixture mark and the reference outcome are separate inputs for another reason. A legitimate visitor guide can use imperative language, so an instruction-like flag need not indicate an attempt to change application behavior. If the human-reviewed task needs that guide, dropping it can break an authorized request. Our example therefore includes a benign marked row. There is also a clear row whose reference label expects a mark. It lets us show the policy's behavior when a signal is missed without embedding any instruction text.

PythonIn [6]
CollapseExpand
fixtures = (
    Fixture(
        Evidence("catalog-map", "Map catalog", "E1", ContentMark.CLEAR), False
    ),
    Fixture(
        Evidence(
            "visitor-guide", "Visitor guide", "E2", ContentMark.INSTRUCTION_LIKE
        ),
        False,
    ),
    Fixture(
        Evidence(
            "restricted-record",
            "Location record",
            "E3",
            ContentMark.INSTRUCTION_LIKE,
        ),
        True,
    ),
    Fixture(
        Evidence("review-fixture", "Reviewed record", "E4", ContentMark.CLEAR),
        True,
    ),
)
assert len({fixture.evidence.source_id for fixture in fixtures}) == len(
    fixtures
)

All four rows model synthetic screening conditions. Their text fields contain only a title and a room code. In particular, a positive reference label carries no attack content and has no special behavior by itself.

Separate observed marks from reference judgments

The labels in the preceding cell play two roles. The input mark is the recorded observation that the policy is allowed to consume. The reference judgment is only for the reviewer who counts errors in a test. If you let the policy read reference judgments, the experiment can give it information it would not have when the system runs. That would make the observed result too optimistic. The evaluator later reads both fields to illustrate misclassification. The policy itself receives only evidence and permission.

Think about the evidence an evaluator needs for a useful review. First decide what should count as a mark and what should count as a benign use of instruction-like language. A short museum or library manual can contain legitimate procedural text. Establish whether the labeling task is about use for an application or the fact that a phrase has imperative grammar. If the reference judgments drift between the two interpretations, the two types of errors mix. The fixtures specify expected marks directly so that the decision exercise does not depend on resolving ambiguous text.

Changes in input distribution can matter even when the policy and the marker software are unchanged. A library adding guides for a new audience could expand the kinds of ordinary procedure described in retrieval. Review representative benign records from that domain before treating a change in mark frequency as evidence of a security event. Mark rates can reflect legitimate variation. Record source availability, relevance, and marking as separate summaries in the operational record so a maintainer can find which variable changed.

A missing mark and a clear mark deserve separate design consideration. The enum in this tiny exercise assumes screening has provided one of its known values. A production integration may receive a missing, failed, or unsupported screening result. The application owner needs a rule for those states and should test that a service timeout lands in the expected branch. For example, a route with a strongly typed course-location field may choose a reduced view if screening is unavailable. Another product may require review before using the source. These are decisions about a particular route's function and risk. The notebook demonstrates neither a default for all applications nor service failure handling.

Notice what we can learn without creating any adversarial strings. By supplying a clear mark for a row whose expected label is positive, we can inspect how sensitive the policy is to an incorrect decision. By supplying a benign marked row, we can inspect whether the task remains feasible. A test that focuses on labels can be repeated by a maintainer with simple inputs and a fixed interpretation. It answers questions about the policy's behavior once it receives the mark; it supplies no measure of a detector's performance.

The policy engine

The fixture starts with an evidence row already in memory. Its access check uses the source identifier and the permission state supplied by the application before building a model-facing view. A row that fails this check produces a denial for every strategy. In a deployment, authorize acquisition at retrieval and enforce the applicable audience conditions again at display. The code then chooses how many fields the caller may use for the answer. The returned decision says what the policy permits for a row. A later component has to build the context from that decision.

PythonIn [7]
CollapseExpand
def decide(
    row: Evidence, visible_sources: frozenset[str], strategy: Strategy
) -> Decision:
    if row.source_id not in visible_sources:
        return Decision.DENY_ACCESS
    if strategy is Strategy.MINIMIZE_ALL:
        return Decision.ROOM_ONLY
    if row.mark is ContentMark.INSTRUCTION_LIKE:
        if strategy is Strategy.REJECT_FLAGGED:
            return Decision.DROP_SOURCE
        return Decision.ROOM_ONLY
    return Decision.ROOM_AND_TITLE

The order of these checks is part of the design. If a marker changes, the authorization result for the same caller and row stays the same. The selected fields can still change for an authorized row. In production, permission state and the record identifier must come from application-controlled identity and resource resolution. A policy model for that wider system needs to state when it reevaluates permission. The NIST zero-trust reference architecture describes ongoing evaluation and revocation when policy requires it. NIST zero-trust reference architecture

PythonIn [8]
CollapseExpand
all_visible = frozenset(fixture.evidence.source_id for fixture in fixtures)
example_row = fixtures[1].evidence
assert all(
    decide(example_row, frozenset(), strategy) is Decision.DENY_ACCESS
    for strategy in Strategy
)

What the decision is allowed to depend on

Each policy rule should have a clear input contract. Our rule receives one evidence row, a set of current source permissions, and a strategy name. It returns a decision. The acceptable branches for a current authorized reader are enumerated. There is a direct denial when the source identifier is absent. The policy has no model callback or arbitrary action hook. That makes the test an exercise in permission and data selection. In the deployed version, a separate enforceable boundary should ensure that this kind of decision governs the actual read and display.

The code passes an opaque identifier to a set membership check. A source title is human-readable context, and a reader can have access to one guide with that title while another copy has different visibility. Treating the title as the authorization identifier would require a separate uniqueness and authority contract. We avoid that assumption in the fixture. The stable identifier binds current permission to the specific evidence row and is held fixed when we compare withdrawn and granted states.

A production design also needs a rule for concurrency. The application may compute a view while the reader still has access and render it later, after a change. The authorization test should observe whichever operation the design claims to protect. If the product requires revocation before display, validate current display authority when the renderer is about to use the stored view. A read-time test is not sufficient evidence for that claim. If read and display happen in the same authorized session under a documented expiry policy, exercise the expiry boundary separately.

Choose semantics for unavailable permissions with the same care. The empty set in this notebook stands for a successful observation that none of these source identifiers may be read. It is a known state. A failed attempt to load permissions is a different situation, even if both result in no data crossing the boundary. Preserve the distinction in any troubleshooting interface. It can help a maintainer see whether a legitimate source disappeared because permission was withdrawn or a dependency could not decide.

The hard part of keeping access separate from content is wiring. A plugin, background parser or renderer should follow the documented authorization rule for the operation it performs. At each normal entry point, inspect whether an earlier decision still applies. For our room lookup, mark and content selection are later stages. Changing the selected view does not widen which source identifiers the caller can use. Modeling those stages separately lets us record the authorization property independently of the projection implementation.

A reason code is useful to check in tests because it survives even when two paths have the same empty reply. Decide how much reason detail belongs in the user-visible interface. A product can show a simple unavailable answer while retaining a scoped operator event that distinguishes denial from content omission. Think about who may see that detail, especially if the existence of a resource is itself sensitive. This notebook prints the full reason for each artificial row because all fixture identifiers and inputs are available to the reader.

Three response strategies

The three strategies share the caller's existing scope. They differ only in the view they construct after the access check succeeds.

  • Reject marked omits marked evidence. A clear authorization result still leaves a flagged source unavailable to the answer.
  • Restrict marked keeps the room field from a marked source. The response still needs to treat it as a reported location from that source.
  • Minimize all passes only the room for every visible source. This makes the field projection independent of the screening mark and omits the display title even from clear evidence.

A field is useful only if it exists and means what the application expects. In this example the room is supplied from a typed catalog record. Our projection is an explicit selection from that record. Cropping a paragraph would produce a different interface and would still leave text open to model interpretation. A narrower view limits which values cross the boundary. Source correctness still needs a separate check.

PythonIn [9]
CollapseExpand
def context_fields(row: Evidence, decision: Decision) -> dict[str, str]:
    if decision is Decision.ROOM_ONLY:
        return {"room": row.room}
    if decision is Decision.ROOM_AND_TITLE:
        return {"room": row.room, "title": row.title}
    return {}
PythonIn [10]
CollapseExpand
def evaluate_row(row: Evidence, permission: frozenset[str], strategy: Strategy):
    decision = decide(row, permission, strategy)
    return decision, context_fields(row, decision)


assert evaluate_row(example_row, all_visible, Strategy.REJECT_FLAGGED) == (
    Decision.DROP_SOURCE,
    {},
)

Check an empty permission set as well as an empty field projection. Both can leave the context empty. Their reason codes differ. In a deployment, this distinction can help maintainers tell an access decision from an evidence-selection decision without recording the raw record.

PythonIn [11]
CollapseExpand
assert evaluate_row(example_row, all_visible, Strategy.RESTRICT_FLAGGED) == (
    Decision.ROOM_ONLY,
    {"room": "E2"},
)
assert evaluate_row(example_row, frozenset(), Strategy.RESTRICT_FLAGGED) == (
    Decision.DENY_ACCESS,
    {},
)

Choose a view by required evidence

Projection works when the application knows which fields it needs. In this example the location inquiry requires the room. A separate question comparing near-identical guides might depend on titles and editions. A minimum-view policy that works for the first task can quietly remove data that the second task needs. Before you narrow the view, ask the team to write down the smallest evidence needed to deliver the current feature. Then test that the approved context still contains it.

The reject strategy makes one choice at the row level. It drops the whole row when the mark is instruction-like. That can be a sensible response when the needed facts cannot be obtained from the record under the chosen policy and better evidence is available. If the marked record is the only source, the workflow needs a careful unavailable or review behavior. Returning an empty answer without context leaves the reader guessing whether they lack access or the library has no result.

The restrict strategy makes a conditional choice at the field level. For marked rows our application takes a room code that it has independently modeled as a catalog field. This produces an answer view only because the field is present and its contents can be checked. When the only record field is an unstructured paragraph, conditional projection is a different problem. An application that asks a model to extract a location needs to assess the extracted value, its source, and its suitability for display. The limited dictionary in this chapter does not do that extraction.

Minimum view is a fixed selection. It helps reviewers verify a constant data contract for the example. A team can check that a response model receives room-only data in every authorized case, independent of one marker's behavior. The cost is that the application denies itself a convenient title even when it could legitimately use that information. A renderer can sometimes recover the title from its own validated view. That creates a separate application-to-renderer path that should still be controlled.

These policies illustrate three distinct choices rather than a ranking. In an application that only needs a room, both kinds of restricted views can deliver the required field for a marked authorized record. Another application might choose to drop the whole record when the desired evidence is unavailable in trusted fields. The example keeps access control fixed for all comparisons, so changing views cannot be interpreted as changing who may read the underlying record.

If you are responsible for a publication or training corpus, ask the application team where projection occurs relative to persistent copies. A minimal model request does not retroactively change a larger retrieval result retained by the application. The application might be able to project in storage or at its retrieval boundary if doing so still supports the user's task. Any extra data copy introduces a requirement to consider its intended audience and retention. Separate that observation from the question of how a model reacts to the fields already in its request.

Worked example

Consider the benign visitor guide. It has an instruction-like mark and the reader has access to it. The reject strategy drops it. The restricted and minimum strategies retain the room so a question about location can still be answered from the guide. When the next view decision receives a permission set without that guide, all strategies deny it before building the view. The replay governs which already-loaded field values can be used for the answer.

PythonIn [12]
CollapseExpand
withdrawn = all_visible - {example_row.source_id}
before = [
    evaluate_row(example_row, all_visible, strategy) for strategy in Strategy
]
after = [
    evaluate_row(example_row, withdrawn, strategy) for strategy in Strategy
]

for strategy, enabled, removed in zip(Strategy, before, after):
    print(f"{strategy.value:16} {enabled[0].value:12} → {removed[0].value}")
ConsoleOut [12]
CollapseExpand
Reject marked    drop source  → deny access
Restrict marked  room only    → deny access
Minimize all     room only    → deny access
PythonIn [13]
CollapseExpand
assert before == [
    (Decision.DROP_SOURCE, {}),
    (Decision.ROOM_ONLY, {"room": "E2"}),
    (Decision.ROOM_ONLY, {"room": "E2"}),
]
assert after == [(Decision.DENY_ACCESS, {})] * len(Strategy)

A permission check does not withdraw data a reader has already seen. If there is a separate display boundary, the deployment has to model what happens to stored results and queued output when access changes. The code evaluates a model-facing view once for each already-loaded row and reevaluates it when the test gives it a new permission set.

Trace one replay without losing the reason

Read the test case after deciding which value is held fixed. The row remains the same visitor guide. The source identifier, room and mark are identical before and after. The strategy may vary across the rows of the printed table but is fixed within each row's before-and-after comparison. The change is the assignment of visible source identifiers. A transition from room only to deny access is therefore evidence about the local decision rule's dependence on current access for that same record.

A useful negative check observes whether denied rows produce any context fields. An application may write a denial reason while inadvertently retaining a selected field in the object used for rendering. The returned pair lets us test the reason and the data independently. For a production test, observe the same property at the actual boundary where information is disclosed. Testing the return value of a helper verifies that helper only. When a separate display stage or a cross-request cache exists, the boundary extends beyond the helper.

Consider what it means for a guide to be the only useful evidence in this run. If access is still present and the policy drops the marked guide, the system cannot use the guide's room value. A fallback could show that the result is unavailable and allow the reader to select a different known source. It should preserve reads within the reader's scope, even when someone requests review. Recovery and escalation deserve explicit permission checks because they may involve a different human operator or a different view of the record.

Another useful replay holds authorization fixed while changing the content label. Start with a named guide with the same title and room. Feed the view builder a clear mark and the instruction-like mark in separate tests, for each strategy. If the policy changes from a full view to a room-only view, that transition is about selection. Access to the source identifier has not changed. If authorization changes in this replay, the application has combined decisions that we meant to keep independent.

You can use these exercises during a local release review with both results and assumptions visible. A duplicate source identifier, an unknown strategy, or a schema error are different scenarios. The code uses fixture objects defined in the notebook and checks uniqueness of their identifiers. A deployable pipeline would have to decide what happens when record resolution fails or when multiple copies have different access decisions. Make that rule explicit before accepting ad hoc behavior as an implementation detail.

Comparing the three strategies

Compare these three strategies on the same four rows with every source visible. A row counts as providing a room when the returned dictionary contains a room key. We also count title keys to show the consequence for context width. Each count has a maximum of four because a row supplies at most one key of each kind.

PythonIn [14]
CollapseExpand
strategy_outputs = {
    strategy: [
        evaluate_row(fixture.evidence, all_visible, strategy)[1]
        for fixture in fixtures
    ]
    for strategy in Strategy
}
PythonIn [15]
CollapseExpand
room_counts = [
    sum("room" in view for view in views) for views in strategy_outputs.values()
]
title_counts = [
    sum("title" in view for view in views)
    for views in strategy_outputs.values()
]
assert room_counts == [2, 4, 4]
assert title_counts == [2, 2, 0]
for strategy, rooms, titles in zip(strategy_outputs, room_counts, title_counts):
    print(f"{strategy.value:16} rooms={rooms}, titles={titles}")
ConsoleOut [15]
CollapseExpand
Reject marked    rooms=2, titles=2
Restrict marked  rooms=4, titles=2
Minimize all     rooms=4, titles=0

Reject marked produces two room values and two titles. Restrict marked produces four room values and two titles. Minimize all produces four room values and no titles. The extra room values in the last two strategies describe coverage of these declared fixtures. They do not measure the truth of the rooms or rate the application against live model behavior.

VisualizationOut [16]
CollapseExpand
Reject marked returns two rooms and two titles. Restrict marked returns four rooms and two titles. Minimize all returns four rooms and zero titles.
Room and title coverage for three policies on the same four authorized fixtures.

Choose the view by what the answer needs. In this fixture any strategy that keeps a room can use it to answer one location question. A later question asking for the display title needs that field from a source the reader may access. Revisit the chosen view when the task changes rather than treating omission of the title as a universal policy.

Read the field counts with their denominator

Each bar counts rows containing a named key. If a room value appears in two different rows, both rows count. The chart does not count unique rooms. It also does not score how helpful the value was to the user. One reason for plotting room and title separately is that they play different roles in this task. A policy could provide the room in every case while omitting record titles, which would be sufficient for the defined lookup fixture but incomplete for a citation feature. The full story depends on which field is required by the question.

The synthetic comparison distinguishes two policy consequences. First, the marked row drops out completely under rejection. Removing a source can reduce the number of available room values and titles. Second, projecting only room preserves one field and removes the other. Statements about a general increase or decrease in security require more information. The figure measures the model-facing field selection for this code. It holds fixed the same four eligible records and uses a preassigned mark for each.

Check reporting when the fixture size changes. Suppose the next test has zero authorized records. All returned views are empty and the counts for rooms and titles are zero. If a team also plots percentages conditional on authorized sources, the denominator is zero and the percentage is undefined. In that state report the sample count and missing percentage. A zero proportion would imply eligible observations were present but did not supply the field. This difference matters when comparing sites or versions with different access patterns.

There is a related comparison between two application versions. A stricter policy may give fewer room values at the same authorization scope. An access change may also give fewer room values while leaving policy unchanged. A view-coverage dashboard should name the denominator and identify which version made the decision. If the application does not record the eligible set for good privacy reasons, it can still use a test with controlled fixtures to check the policy and reserve production observations for questions about availability patterns.

Separate this policy view from detector evaluation. We could change the marker and keep the policy fixed, or change the policy and keep the marker fixed. The fixture comparison changes policy and uses identical labels. That choice is what allows a clean attribution of the field count differences to the view strategy. Measuring a detector would need reviewed examples and an evaluation procedure for the relevant source population. The plotted values offer no basis to infer such a measurement.

What the marker gets wrong

The visitor guide shows a false positive. Its reference judgment is clear but its mark is instruction-like. The reviewed record shows a false negative. Its reference judgment expects a mark but its supplied mark is clear. Compare those mismatches before reading the policy results. That keeps a bad content judgment distinct from the question of which fields an authorized view contains.

PythonIn [17]
CollapseExpand
false_positives = [
    item.evidence.source_id
    for item in fixtures
    if item.evidence.mark is ContentMark.INSTRUCTION_LIKE
    and not item.review_expects_mark
]
false_negatives = [
    item.evidence.source_id
    for item in fixtures
    if item.evidence.mark is ContentMark.CLEAR and item.review_expects_mark
]
assert false_positives == ["visitor-guide"]
assert false_negatives == ["review-fixture"]

For these assignments the false-positive rate is one divided by two. It divides false positives by the number of reference-negative rows. The false-negative rate is also one divided by two. It divides false negatives by the number of reference-positive rows. Both denominators are nonzero in this exercise. They must be checked before computing rates on a different set. These rates describe four fixtures chosen for teaching, so they provide no detector performance estimate.

PythonIn [18]
CollapseExpand
reference_negatives = sum(not item.review_expects_mark for item in fixtures)
reference_positives = sum(item.review_expects_mark for item in fixtures)
assert (reference_negatives, reference_positives) == (2, 2)
print(
    f"Fixture false-positive rate: {len(false_positives) / reference_negatives:.0%}"
)
print(
    f"Fixture false-negative rate: {len(false_negatives) / reference_positives:.0%}"
)
ConsoleOut [18]
CollapseExpand
Fixture false-positive rate: 50%
Fixture false-negative rate: 50%

Review errors in context

A false positive in a screening report can have different consequences depending on what the application does next. In the example, a marked benign row can still deliver its room in the restricted view. If another feature needs the title, the same restriction can remove needed evidence. Rejection removes both. To interpret a reported error, read the Mark field alongside the decision and the expected answer requirements. A high-level rejection count by itself will not tell you how many authorized tasks were blocked.

False negatives are also conditional on downstream use. A missed screen does not automatically mean the application took a disallowed action. In this example access is checked independently and the only extra field compared with minimum context is a display title among authorized rows. In a different application, a miss could matter if unconstrained model output drives downstream behavior. Testing the policy boundary requires checking what capabilities exist, what the model can influence, and where policy is enforced. A count can flag an area for investigation without proving a downstream outcome.

If you maintain a real policy, collect benign examples from the collections users retrieve. For the purposes of a controlled test, annotate whether the record is relevant to the task, whether the known mark should be emitted, and what evidence should survive the policy under each access scenario. The first two judgments can disagree. An instruction-like visitor guide can be especially relevant to a question about visitor procedure. A harmless but irrelevant record can remain irrelevant no matter what the marker says.

Include coverage across source groups used in the product. Many libraries provide guides in several languages, even in the same department. If markers are evaluated only on records from one collection, the observed error rates characterize that sample. Adding another collection may require new calibration evidence, not copying the old rates. Track what input population was reviewed in controlled tests and distinguish coverage statistics from events confirmed in the app.

In applications where manual review is feasible, give the reviewer source provenance and reason for restriction without granting new authority through the review UI. They can decide whether one item is legitimate evidence for the designated task and send uncertain cases to an authorized owner. Write down what future policy behavior changes after a reviewed case. A one-off decision may be specific to one resource. A change to a global content rule can affect other readers and document types, so it needs a broader review.

Monitoring and the residual-risk view

For a defensive test, pick a legitimate task and vary one input at a time. The guide example varies permission with the mark, source, and strategy held fixed. The strategy comparison varies the strategy with the inputs and permission fixed. That separation makes it possible to attribute a changed decision to the variable you changed.

For a change review, record the policy version, decision code, and provenance for the operator who needs to investigate a discrepancy. Establish what can be stored and for how long. Source content and authorization state can be sensitive, so the example shows aggregate decision counts and holds the fixture data in memory.

PythonIn [19]
CollapseExpand
from collections import Counter

decisions_by_reason = Counter(decision.value for decision, _ in before + after)
assert decisions_by_reason == {
    "drop source": 1,
    "room only": 2,
    "deny access": 3,
}
print(dict(decisions_by_reason))
ConsoleOut [19]
CollapseExpand
{'drop source': 1, 'room only': 2, 'deny access': 3}

Use decision logs to ask a bounded question

The examples above produce small summaries of policy decisions. A product may record similar reason codes to answer operational questions. An increase in dropping a marked source could follow a policy update, a changed mix of guides, or greater volume. Without comparing a consistent denominator and version, an increased count alone gives little guidance. Separate this sort of usage signal from an incident finding. A maintainer needs enough detail to trace whether people could still complete authorized tasks and whether unexplained state changes occurred.

If an authorized task fails, the support team may need to know whether the source was unavailable, its access was denied, its content was marked, or the renderer could not answer. Give operators a way to identify that stage without requiring them to read every user's prompt or document. A policy version, scope identifier with appropriate minimization, and reason code can be enough to reproduce a similar case using artificial data. When reproducing authorization choices, include the intended state explicitly in the fixture. Avoid relying on reproduction against a live reader account.

Review operational metrics when moving the boundary. Suppose the application starts trimming views at retrieval rather than just before model input. It may count policy decisions earlier, before records are grouped for a response. The same reason codes then describe a different unit, perhaps source rows instead of displayed answers. A chart comparing before and after needs to document that change. For an incident review, make clear which events were observed at each boundary and which steps are functional assumptions.

The purpose of capturing different outcomes is to avoid turning a clear mark into a statement of trust. What a marker found describes a weak observation about source content. What the application permitted describes a decision made with current identity and scope. What showed in the UI describes a rendered result under the application's checks. The categories may appear as separate events with a common test-case ID. Compare them using a local replay where the test controls what changed. Keep incident data handled within the application's approved access boundary.

A practical regression exercise also includes an authorized source needed to complete the task after restriction. It checks that the user can still complete the task with the selected view. A security test that only checks restriction can reward removing all evidence. An availability test that ignores permission can reward retaining evidence past an access boundary. Require both properties for the route where the notebook describes a room lookup. Their separation gives operators a way to fix the failing mechanism without making the passing mechanism weaker.

Limitations and impact

A deployment still needs to check that its enforcement boundary is on every path to the capability. In the notebook all paths are function calls that share the same authorization predicate. In other designs a renderer, cache, or follow-up request can have its own boundary. Also, the code assumes catalog fields were already available in the declared type. The room value could still be inaccurate. Solving that problem belongs with data validation and provenance.

A useful regression test checks an authorized source with a benign mark, an authorized clear source, and a source with withdrawn permission. Compare the reason codes and chosen fields. For the authorization property, verify the denies across all content policies. For the usefulness property, check that the chosen fields still answer the user's original question. The two tests can disagree without either test being wrong.

What this exercise leaves to the application

The policy example is an in-memory decision function, so it represents a local snapshot of permissions. It does not represent a distributed transaction that checks authorization and delivers a result at the same instant. When a deployment needs a strong revocation semantics across services, the team has to choose where authority is checked and how older results are invalidated or rechecked. Client-side display alone cannot retroactively change what was disclosed. Write requirements in terms of future reads, future displays, and prior disclosures so each can have the right treatment.

Similarly, we choose the room from an existing field. A deployed catalog may use broad text or third-party records that lack suitable fields. There the application must decide whether to avoid a model interpretation, extract information with a bounded result format and validate it elsewhere, or require a different source. A narrower result schema can check that the application receives a field in the expected shape. Whether that field corresponds to a valid room will still depend on its source and the check used to validate it.

There is no measurement here of an actual system's rate of unsafe behavior. The data sets are hand-selected and the program has minimal branching and no learned component. That is valuable for regression because all expected outcomes are inspectable. To learn about a deployed workflow you would need end-to-end assurance about all real entry points and independent measurements that use representative authorized and benign cases. The limited experiment makes it easier to explain how a decision changed before moving to deployment-specific tests.

When a content policy applies unexpectedly to an ordinary user, the product should have a bounded way to handle it. In a library, a maintainer can inspect whether a guide was presented as data, whether the room field exists, and whether the reader was allowed to use it. They do not need the application to grant broad permissions to resolve that issue. This is another reason to distinguish resource authorization, evidence use, and support workflows in the threat model. An appeal or request for correction can go to an authorized human owner with enough context to decide.

One final check connects all the cases. For a supported task, write down the data that must arrive, the current permission that must hold, and the ways a fixture can vary. Check both the desired values and the behaviors under different permission states. Where interpretation is uncertain, write the uncertainty into the view or the final response instead of presenting a plausible unsupported location.

Replay the permission and mark axes independently

We can write all expected outcomes for one known row as a small table. The first axis is whether the current source identifier is visible. The second is which of the two fixture marks the row carries. The remaining dimension is the selected view strategy. With two visibility states, two marks and three strategies, the product contains twelve cases. This calculation applies to this selected row and these two-state inputs. It does not count all possible production inputs or claim to establish coverage of the application's entry points.

Use this table as a check on code structure. A source that is outside the current authorization should lead to denial across all strategies and marks. Once authorized, rejecting or narrowing the view changes how much evidence survives. These are two stages of one decision, with different invariants. We can vary the screening input by making a second copy of our one fixture row. This requires no new source text and fires no side effects.

PythonIn [20]
CollapseExpand
from dataclasses import replace
from itertools import product

replay_grid = {}
for eligible, mark, strategy in product((False, True), ContentMark, Strategy):
    replay_row = replace(example_row, mark=mark)
    permissions = all_visible if eligible else withdrawn
    replay_grid[eligible, mark, strategy] = evaluate_row(
        replay_row, permissions, strategy
    )
assert len(replay_grid) == 2 * len(ContentMark) * len(Strategy)

Check the six denied rows first. Every row in that half of the table should pair the same denial reason with an empty view. Then examine the eligible half. The minimum policy preserves the room for both marks. The restrict policy keeps a title only for the clear mark. The reject policy omits the instruction-like row and retains the two fields for the clear mark. Reviewing the entire table for the declared row protects against a change that accidentally moves the marker branch ahead of the authorization test.

PythonIn [21]
CollapseExpand
denied_result = (Decision.DENY_ACCESS, {})
for mark, strategy in product(ContentMark, Strategy):
    assert replay_grid[False, mark, strategy] == denied_result

clear_view = (Decision.ROOM_AND_TITLE, {"room": "E2", "title": "Visitor guide"})
room_view = (Decision.ROOM_ONLY, {"room": "E2"})
assert (
    replay_grid[True, ContentMark.CLEAR, Strategy.REJECT_FLAGGED] == clear_view
)
assert (
    replay_grid[True, ContentMark.CLEAR, Strategy.RESTRICT_FLAGGED]
    == clear_view
)
assert replay_grid[True, ContentMark.CLEAR, Strategy.MINIMIZE_ALL] == room_view
assert replay_grid[
    True, ContentMark.INSTRUCTION_LIKE, Strategy.REJECT_FLAGGED
] == (
    Decision.DROP_SOURCE,
    {},
)
assert (
    replay_grid[True, ContentMark.INSTRUCTION_LIKE, Strategy.RESTRICT_FLAGGED]
    == room_view
)
assert (
    replay_grid[True, ContentMark.INSTRUCTION_LIKE, Strategy.MINIMIZE_ALL]
    == room_view
)

The two permission states in this replay are conditions chosen by the test author. They are neither a claim about how often access is withdrawn nor a model of how quickly distributed permission changes arrive. Keep the recorded fixture input beside the expected outcome. If a deployment later adds pending approval as a third condition, define what the current user should see and which fields are allowed to reach the answer stage. Test the transition when the approval is granted, and test the case where it never arrives. The original decision space has only two permission conditions and remains useful for the tasks that share that contract.

The complete table gives one thing that the three-row worked example cannot. It checks that a row marked clear still loses access on the next evaluation, even when the policy would normally pass its broadest view. You can keep that rule as a regression test when you change eligibility calculation or add a fourth policy. Update the set of assertions and its expected denominator when the declared state space changes.

Permission and projection tests should use different fixture controls. To test identity-to-permission resolution, feed an application test a known reader identity and examine which source IDs it considers visible. To test the projection code, supply a permission set and an evidence row directly. An error resolving identity will not show up in a pure function that only receives a set. An error in view construction can show up there even if account permission assignment is correct.

You could also compare the six eligible cases by how much data arrives. Of the eligible cases, exactly one produces an empty view, three produce room only, and two produce both fields. The grouped counts describe the marked and clear variants of this one source. They should differ from the earlier figure, whose unit was across four sources with their original marks. Keep these experiments separate because repeating the same source at two labels is a different fixture arrangement.

PythonIn [22]
CollapseExpand
eligible_decisions = Counter(
    decision
    for (eligible, _, _), (decision, _) in replay_grid.items()
    if eligible
)
assert eligible_decisions == {
    Decision.DROP_SOURCE: 1,
    Decision.ROOM_ONLY: 3,
    Decision.ROOM_AND_TITLE: 2,
}

This outcome summary does not weight cases by how likely each state is. It counts each legal combination once as part of a table of expected behavior. That is useful for finding an untested branch. It does not tell you the proportion of deployed requests expected to produce any of those decisions.

Summary

Retrieved content can inform an answer. Application state determines which records the reader may access. The fixture shows how a content mark can reduce coverage by flagging an ordinary guide and how the room field can survive that mark under a narrower view. The same row loses access under all three strategies when the caller's permission is withdrawn before the next decision.

Key Parameters

The examples vary inputs to a local decision function. The parameters below record the interpretation of each test input, along with what would have to change for the interpretation to apply to another task.

ParameterValue in the fixtureWhat to check in a deployment
Source identifierOne stable identifier per artificial rowResolve canonical resource identity before asking whether the reader is allowed to use it.
Content markClear or instruction-like, assigned by the fixture authorEvaluate the real screening system on appropriately reviewed data. Specify how its runtime errors affect the view.
Current visibilitySet of source IDs supplied separately to the pure decisionVerify the caller's scope and define when changes are rechecked on the read and display paths.
View strategyReject marked, restrict marked, or minimize allEnsure the available fields satisfy the approved task and reach only the intended consumer.
Required fieldRoom, assumed present and typed in every fabricated rowCheck missing and invalid room values independently of the authorization and marker logic.
CountsOne contribution per row and field key in the view comparisonUse a denominator that matches the comparison and identify any change of unit across versions.

When a new feature requires richer evidence, extend the test from the task contract. If a question needs two fields, use a specimen that requires both. If current permission is revoked before display, build a separate test for that boundary. If a new source does not provide structured fields, agree on an extraction and validation interface before assuming that its context is comparable to the room-only projection. The policy decisions in this chapter remain testable even when a later design adds its own extraction and rendering checks.

When presenting these checks to a maintainer, give each an expected failure that shows what it protects. For the authorization requirement, the expected failure is denial with an empty view after access is absent. For the narrow evidence requirement, a permitted row still lacks the title under minimum context. For the availability property, an eligible marked source keeps its room under the restricted policy. Keeping these outcomes separate supports changes to any one layer without erasing what the others are expected to enforce.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about indirect prompt injection and separating access control from content policy.

Indirect Prompt Injection and Content Policy

Question 1 of 80 of 8 completed
In the chapter's framing, what distinguishes indirect prompt injection from direct injection?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 19

Tool, Retrieval, and Memory Poisoning

Learn how tool schemas, retrieval snapshots, and durable memory lose integrity. Validate, authorize, and quarantine records across boundaries.

34 min read
Language AI Handbook · Vol. 19

Agent Supply Chains and Protocol Security

Build a release gate for agent tool supply chains. Verify artifacts, detect drift, and enforce revocation and least privilege.

35 min read
Language AI Handbook · Vol. 19

Audit, Detection, and Incident Response

Design tamper-evident audit trails, build layered detectors that survive base rates, and run incident response with kill switches and evidence preservation.

50 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026indirectprompt, author = {Michael Brenndoerfer}, title = {Indirect Prompt Injection}, year = {2026}, url = {https://mbrenndoerfer.com/writing/indirect-prompt-injection-policy-evidence-views}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Indirect Prompt Injection. Retrieved from https://mbrenndoerfer.com/writing/indirect-prompt-injection-policy-evidence-views
MLAAcademic
Michael Brenndoerfer. "Indirect Prompt Injection." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/indirect-prompt-injection-policy-evidence-views>.
CHICAGOAcademic
Michael Brenndoerfer. "Indirect Prompt Injection." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/indirect-prompt-injection-policy-evidence-views.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Indirect Prompt Injection'. Available at: https://mbrenndoerfer.com/writing/indirect-prompt-injection-policy-evidence-views (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Indirect Prompt Injection. https://mbrenndoerfer.com/writing/indirect-prompt-injection-policy-evidence-views
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy