Audit, Detection, and Incident Response › Code implementation: a small, end-to-end response harness

Michael BrenndoerferDecember 2, 20266 min read
Language AI HandbookAll chapters
Part 61 of 67Agentic AI and Protocol Security
Chapter 471Audit, Detection, and Incident Response › Code implementation: a small, end-to-end response harness
Reading section 7 of 10 · Code implementation: a small, end-to-end response harness · 6 minSection 7 of 10 · 6 min

Section 7 of 10 · 6 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

We now assemble the pieces into a compact, deterministic, in-process harness using only invented fixtures. It demonstrates the policy layer, the kill switch as an external enforced flag, and an incident timeline: the operational glue that connects detection to response. There are no payloads, credentials, or live targets; every record is synthetic and every label is inert.

The ControlPlane supplies a decision to the mock gateway. The Responder records the incident timeline. The coverage check submits only the supplied mock tool labels through that gateway.

The gateway writes a reduced event mapping with an action type, a mock tool label, a decision, and a reason. The full audit envelope above would also require event and trace identifiers, time, principals, and chain fields. This fixture exercises the decision boundary with a shared in-process object.

PythonIn [19]
CollapseExpand
from dataclasses import dataclass, field

INERT_DECISIONS = {"allow", "deny", "escalate"}


@dataclass
class ControlPlane:
    # In a real deployment this is external state (a gateway/sidecar config),
    # not something the agent holds. Here it is a shared object for the demo.
    global_halt: bool = False
    halted_tools: set = field(default_factory=set)
    allowed_tools: set = field(
        default_factory=lambda: {"mock_read", "mock_transfer"}
    )

    def permit(self, tool: str):
        if self.global_halt:
            return "deny", "global_halt"
        if tool in self.halted_tools:
            return "deny", "tool_halted"
        if tool not in self.allowed_tools:
            return "deny", "not_authorized"
        return "allow", "ok"


def gateway_action(control, tool, audit):
    decision, reason = control.permit(tool)
    assert decision in INERT_DECISIONS
    audit.append(
        {
            "action_type": "tool_call",
            "tool": tool,
            "decision": decision,
            "reason": reason,
        }
    )
    return decision

The permit method checks the global flag first, then the named tool’s hold, and finally the allowlist. This gives a defined reason when several checks could deny the same mock label. The assert in the gateway checks a fixture invariant. Python can omit assertions in optimized mode. Implement required runtime enforcement with explicit checks at the production authority boundary.

Next, a thin responder that ties the chained audit (reusing build_chain and verify_chain from earlier) to the control plane, and a timeline builder. The responder exposes exactly the operations the lifecycle requires: preserve, contain, investigate, and recover.

PythonIn [20]
CollapseExpand
class Responder:
    def __init__(self, control, audit):
        self.control = control
        self.audit = audit
        self.pinned_head = None  # frozen at preservation time
        self.evidence_snapshot = None  # independent local copy of the trail
        self.timeline = []

    def _stamp(self, step, detail=""):
        self.timeline.append({"step": step, "detail": detail})

    def preserve(self):
        from copy import deepcopy

        self.evidence_snapshot = build_chain(deepcopy(self.audit))
        self.pinned_head = (
            self.evidence_snapshot[-1]["record_hash"]
            if self.evidence_snapshot
            else GENESIS
        )
        self._stamp("preserve", f"head={self.pinned_head[:8]}")

    def contain_global(self):
        self.control.global_halt = True
        self._stamp("contain", "global_halt_enabled")

    def contain_tool(self, tool):
        self.control.halted_tools.add(tool)
        self._stamp("contain", f"tool_halted:{tool}")

    def investigate(self):
        ok, _ = verify_chain(self.evidence_snapshot, self.pinned_head)
        if not ok:
            self._stamp("investigate", "integrity_check_failed")
            return False, None
        denies = sum(
            1
            for e in self.evidence_snapshot
            if e["payload"].get("decision") == "deny"
        )
        self._stamp("investigate", f"integrity={ok} denies={denies}")
        return ok, denies

    def recover(self, tool):
        self.control.halted_tools.discard(tool)
        self._stamp("recover", f"tool_restored:{tool}")

The snapshot copies the local event dictionaries, including nested values, before it builds the chain. The saved digest is kept separately in the responder object to show the verification procedure. In a deployment the snapshot and checkpoint need independent storage and access controls. This local object has no write-once enforcement.

The example permits a mock write, saves the record, and temporarily suspends that tool. After checking the snapshot, it clears the narrow local hold and exercises the same mock action. Every operation is an in-process label.

PythonIn [21]
CollapseExpand
control = ControlPlane()
audit = []

# Normal operation: an action the policy permits
gateway_action(control, "mock_transfer", audit)
gateway_action(control, "mock_read", audit)

# Detection signal -> declare incident, then respond in lifecycle order
resp = Responder(control, audit)
resp.preserve()  # FIRST: freeze evidence
resp.contain_tool("mock_transfer")

# Post-containment attempt must now be denied by the gateway
post = gateway_action(control, "mock_transfer", audit)

ok, denies = resp.investigate()
if not ok:
    raise RuntimeError("Preserved snapshot did not match its checkpoint.")
resp.recover("mock_transfer")
restored = gateway_action(control, "mock_transfer", audit)
assert post == "deny" and restored == "allow"
ConsoleOut [22]
CollapseExpand
Post-containment decision: deny

After fixture recovery: allow
Incident timeline:
  preserve     head=72c0dc73
  contain      tool_halted:mock_transfer
  investigate  integrity=True denies=0
  recover      tool_restored:mock_transfer

Evidence integrity : True
Denials in snapshot: 0
Preserved snapshot still verifies: True

Preservation happens before containment in this replay. The saved snapshot contains the two events already recorded when the hold is applied. The next mock request is denied and logged separately in the live list. Investigation verifies the saved snapshot against its stored head and counts denials in that snapshot.

The snapshot has zero denials because it contains only two earlier permitted events. The mock tool denial appears in the live list after that snapshot. The second integrity check confirms that the copied prefix still matches the saved digest.

Making the snapshot complete relative to reality

The chain check establishes that the preserved snapshot agrees with its pinned head. A route that never emitted an event would leave no record to check. In a drill, compare the emitted events with a route inventory maintained outside the logger.

The probe checks events emitted by the mock gateway for a specific set of supplied labels. A newly added path is exercised only when an independent route inventory includes it and the drill drives that path.

PythonIn [23]
CollapseExpand
def completeness_probe(control, gateway_tools):
    expected_tools = set(gateway_tools)
    covered = set()
    for tool in expected_tools:
        events = []
        decision = gateway_action(control, tool, events)
        if (
            len(events) == 1
            and events[0]["action_type"] == "tool_call"
            and events[0]["tool"] == tool
            and events[0]["decision"] == decision
            and (tool in control.allowed_tools or decision == "deny")
        ):
            covered.add(tool)
    return covered == expected_tools, covered


covered_ok, covered = completeness_probe(
    ControlPlane(), control.allowed_tools | {"unknown_tool"}
)

The probe includes "unknown_tool" to check that a denied mock label still produces one matching tool_call event. A gateway return without a matching record fails this fixture check.

ConsoleOut [24]
CollapseExpand
All supplied mock labels recorded: True
Recorded mock labels: ['mock_read', 'mock_transfer', 'unknown_tool']

The exercise covers each supplied mock tool label, including a denied unknown label. It says nothing about real paths beyond the modeled gateway. A production test can compare observations against an inventory of actual independent side-effect routes.

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!

Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy