Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 06 · 40 minutes

Write incident playbooks for AI and check them with code

After this lesson you can
  • Write a playbook for each of five AI incident types
  • Name a trigger, first actions, an owner, evidence and communication in each
  • Check every playbook with a script that fails when a section is missing
Lab files of this lesson (23)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

At 03:10 the alert A-INJ fires. The engineer on call has used Orbi for a week and has never seen an incident. The detectors of lessons 2 to 5 tell her that something happened. They do not tell her what to do, whom to wake or what to keep. You write the playbooks before the night comes, and you add a checker so that a playbook with a missing section never reaches the shared folder.

Recall

Lesson 2: what does a record alert tell the reader, and what does a user alert tell?

A record alert says "read this request", for example a tool that ran after an untrusted document. A user alert says "look at this person's day", for example a high refusal rate. The playbook for each alert must say which one it starts from.

Lesson 5: why does the model-theft playbook start with a check of the allow-list?

A known integration such as the partner batch looks like an extractor. The first action is to ask its owner before any block. Acting on a known user without asking turns a false alert into an outage.

The idea

"Security fundamentals" (lesson 6) gave you the steps of a response: prepare, detect, contain, eradicate, recover and learn. "Security operations basics" (lessons 11 to 13) teaches evidence and runbooks; here you apply them to an AI system. NIST SP 800-61 Revision 3 (April 2025) places incident response inside the NIST Cybersecurity Framework 2.0. Take the current text from NIST. A playbook is the part of the preparation that people use at 03:10: a short file for one kind of incident. Five sections make it usable:

SectionThe question it answers
TriggerWhich alert, and what makes it this kind of incident?
First actionsWhat do I do in the first hour, in order, and what do I leave alone?
OwnerWho leads, and who decides what?
EvidenceWhat do I keep, so that the review can tell what happened?
CommunicationWho is told what, and who is not to say anything?

Each alert has an id, and lesson 9 prints it in the kit report. The id picks the playbook:

IdRaised byPlaybook
A-INJRecord score of 2 or more (lesson 2)injection-tool-misuse
A-REFUSEHigh refusal rate of a user in a day (lesson 2)none: a signal for the trend
A-DRIFTPSI above the threshold (lesson 3)poisoned-knowledge-base
A-RATE, A-COSTA spike, a user over the hourly limit, a day over budget (lesson 4)runaway-cost (your turn)
A-EXTRACTA user flagged by the extraction rule (lesson 5)model-theft
A-LOG-SECRETA secret or a personal item in the log (lesson 1)log-secret
A-LEAKA report that the assistant gave out data; no detector here raises itdata-leak
From an alert to a closed incident
AlertPlaybookFirst actionsEvidenceCommunicationthe alert id picks the filecontain before you analysekeep the records under holdtell the ownersAlertPlaybookFirst actionsEvidenceCommunication1234
  1. Alert → Playbook: the alert id picks the file
  2. Playbook → First actions: contain before you analyse
  3. First actions → Evidence: keep the records under hold
  4. Evidence → Communication: tell the owners

Worked example

1. Write the first playbook

A playbook is a Markdown file: a title, and five sections that start with ### . The first one is for the incident of lesson 2: an injection that made the assistant use a tool. Save it as playbooks/injection-tool-misuse.md. It names real commands of respond.py, which lesson 7 builds. A name in capital letters (DOC_ID, KEY_NAME) is a value that the engineer fills in at 03:10 from the alert. grep PATTERN FILES prints the lines that hold the pattern, and logs/*.jsonl means every week of the log.

playbooks/injection-tool-misuse.md

# Prompt injection with tool misuse

### Trigger

Alert A-INJ where the tool rule fired: an action tool ran after the assistant read untrusted content.

### First actions

1. Disable the tool that acted: `python3 respond.py disable-tool send_email_external`.
2. Find every record with the same document id and list the users that it touched: `grep DOC_ID logs/*.jsonl`.
3. If data may have left, revoke the key that the tool used: `python3 respond.py revoke-key key-mail-gateway`. If more records match, run `python3 respond.py safe-mode on`.

### Owner

The on-call AI engineer. The security lead decides on a notice to customers.

### Evidence

Keep the records of the alert and of the same document id, the registry and config files, and the changes file. Put a hold on them.

### Communication

Tell the security lead within one hour. Tell the customer success lead what the assistant did to the users listed.
One first action, in parts
1.the orderpython3 respond.pythe switch script of lesson 7disable-toolthe actionsend_email_externalthe target1.the orderpython3 respond.pythe switch script of lesson 7disable-toolthe actionsend_email_externalthe target

2. Write the other four

A data leak through the model, a secret in the log, a poisoned knowledge base and model theft. Each Trigger names an alert id, and each first action is a command that you can type. The two leaks are two incidents: in one the assistant gave out data, in the other the log writer stored a secret.

playbooks/data-leak.md

# Data leak through the model

### Trigger

Alert A-LEAK (a report that the assistant gave out data), or A-INJ where the response was very long after a known phrase.

### First actions

1. Switch to safe mode so that the assistant stops using retrieved documents: `python3 respond.py safe-mode on`.
2. Find the secret or the data class that left, and revoke any key that was shown: `python3 respond.py revoke-key KEY_NAME`.
3. List the users whose data may be in the answers, from the records that the alert names: `grep -E 'RECORD_1|RECORD_2' logs/*.jsonl`.

### Owner

The security lead. The data protection officer is told at once.

### Evidence

The records of the window, the sizes of their responses, the scan result, and the list of rotated keys. Do not copy the leaked text into the ticket.

### Communication

Note the time that you became aware. The data protection officer decides on notices to users and to the authority: the GDPR (Article 33) asks for the notice to the authority within 72 hours of awareness, where feasible. Nobody else sends a message about the leak.

playbooks/log-secret.md

# Secret or personal data in the log

### Trigger

Alert A-LOG-SECRET: the kit reports records with something that must not be logged. This is a fault of the writer, not a leak through the model.

### First actions

1. Count and list the records: `python3 kit.py logs/week2.jsonl` and the scan of lesson 1, step 5.
2. Stop the writer that made them, or fix its masks in `logrec.py`, and prove the fix: `python3 test_logrec.py`.
3. Remove the records from the log and from every copy of it, and keep only a list of their ids.

### Owner

The owner of the log store. The data protection officer is told if personal data was stored.

### Evidence

The ids of the records, the name of the kind of item (a key, a card), the time of the first and last record, and the test that now covers it. Do not copy the item into the ticket.

### Communication

Tell the security lead within one hour. If a key was stored, tell the owner of the key to rotate it.

playbooks/poisoned-knowledge-base.md

# Poisoned knowledge base

### Trigger

Alert A-DRIFT after an ingestion run, or alert A-INJ where one document id appears in two or more alerts.

### First actions

1. Pause ingestion so that no new document enters the index: `python3 respond.py pause-ingest`.
2. Roll back to the last known-good index version in the registry: `python3 respond.py rollback index kb-v6`.
3. Check the answers with the test set: `python3 respond.py verify`. Then list the documents added since that version for review.

### Owner

The data owner of the knowledge base, with the on-call AI engineer.

### Evidence

The ingestion log with the source of each new document, the drift numbers by day, and the registry entry of the index that you left.

### Communication

Tell the owner of the source that supplied the document. Tell support that answers may have been wrong since the ingestion date.

playbooks/model-theft.md

# Model theft by extraction

### Trigger

Alert A-EXTRACT: a user sends many diverse requests with one fixed start and almost no repeats, over days or hours.

### First actions

1. Check the user against the allow-list of known integrations (`python3 -c "import extract; print(extract.allowed_users())"`) and ask its owner.
2. If it is unknown, revoke its key (`python3 respond.py revoke-key KEY_NAME`) and lower its limit: `python3 respond.py limit-user USER_ID 5`.
3. Search the earlier weeks for the same user id and for users with the same request shape: `grep USER_ID logs/*.jsonl`.

### Owner

The product owner of the model. The on-call AI engineer does the technical work.

### Evidence

The features of the user (requests, busiest day, repeat share, sweep share), the first and last record ids, and the key that was revoked.

### Communication

Tell the legal contact if the terms of use were broken. Do not contact the user until legal agrees.

3. Write the checker

check_playbooks.py reads every .md file of a folder (Path(folder).glob("*.md") lists them). re.split cuts a text at every match of a pattern, here at each line that starts with ### . A playbook passes only when all five sections exist and have at least five words, when the Trigger names an alert id such as A-INJ, and when the first actions have at least three numbered steps. The script prints one line for each file and ends with exit code 1 if any file fails, or if the folder has no playbook at all. A checker that finds nothing must not report success.

check_playbooks.py

"""check_playbooks.py: every playbook needs five sections with text, and its trigger must name an alert id.

    python3 check_playbooks.py [folder]      default folder: playbooks. Exit code 1 if any playbook has a problem.
"""
import re
import sys
from pathlib import Path

SECTIONS = ["Trigger", "First actions", "Owner", "Evidence", "Communication"]
ALERT_ID = re.compile(r"\bA-[A-Z]+\b")          # for example A-INJ
NUMBERED = re.compile(r"(?m)^\d+\. ")           # a line that starts like "1. "


def sections(text):
    """A dictionary from the heading of each `### ` section to its text."""
    parts = re.split(r"(?m)^### +(.+)$", text)
    return {parts[i].strip(): parts[i + 1].strip() for i in range(1, len(parts) - 1, 2)}


def problems(text):
    found, out = sections(text), []
    for name in SECTIONS:
        if name not in found:
            out.append(f"missing {name}")
        elif len(found[name].split()) < 5:
            out.append(f"{name} is too short")
    if "Trigger" in found and not ALERT_ID.search(found["Trigger"]):
        out.append("Trigger names no alert id")
    if "First actions" in found and len(NUMBERED.findall(found["First actions"])) < 3:
        out.append("First actions has fewer than 3 numbered steps")
    return out


def main(folder):
    files = sorted(Path(folder).glob("*.md"))
    bad = 0
    for f in files:
        found = problems(f.read_text())
        bad += bool(found)
        print(("FAIL " if found else "ok   ") + f.name + (": " + "; ".join(found) if found else ""))
    print(f"playbooks ok: {len(files) - bad} of {len(files)}")
    return 1 if bad or not files else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "playbooks"))

4. Check the five playbooks

python3 check_playbooks.py playbooks
echo "exit code $?"
ok   data-leak.md
ok   injection-tool-misuse.md
ok   log-secret.md
ok   model-theft.md
ok   poisoned-knowledge-base.md
playbooks ok: 5 of 5
exit code 0

5. Check a flawed playbook

A colleague wrote a playbook in a hurry. Save it as broken/runaway-cost.md and check it.

broken/runaway-cost.md

# Runaway cost

### Trigger

Alert A-COST: the cost of one day is over the budget of the assistant.

### First actions

1. Look at the cost report.
2. Find the user.

### Owner

### Evidence

The cost report of the day, the top users by cost, and the records of the busiest hour.

### Communication

Tell the finance lead and the product owner within the same day.
python3 check_playbooks.py broken
echo "exit code $?"
FAIL runaway-cost.md: Owner is too short; First actions has fewer than 3 numbered steps
playbooks ok: 0 of 1
exit code 1

The Owner section is empty, and the first actions have two steps. "Look at the cost report" is not wrong, but it is not enough at 03:10: which report, which command, which tool is disabled?

Your turn

Files you need: check_playbooks.py, the folder playbooks and broken/runaway-cost.md (kr-lab.sh for this lesson). Repair broken/runaway-cost.md for the alerts A-COST and A-RATE. It needs an owner (a role, not a name, in at least five words), and at least three numbered first actions with the commands of the lab: the cost report of lesson 4 (python3 run_cost.py) and the user limit of lesson 7 (respond.py limit-user). Copy the repaired file into the folder playbooks. Then check playbooks again.

Also check an empty folder: make one with mkdir empty and run the checker on it.

Check yourself

Why do the first actions say "contain before you analyse"?

Every minute that the tool stays on, the injection can act again. Contain with the smallest action that stops the harm, keep the records, then find the cause. A containment can be undone. Damage that goes on cannot.

Why must the Owner section name a role and not a person?

People are on leave, ill or have left. A role such as "on-call AI engineer" is on a rota, so someone always holds it. The playbook names the role, and the rota names the person.

The playbook for a data leak says that nobody except the data protection officer sends a message about it. Why is that useful?

A leak has legal duties, such as notices to users and to authorities, and a wrong or early message makes them harder. One voice keeps the facts the same.

What can the checker not tell you?

It tells you that the sections exist, not that the content is right or that the people can do the steps. Only an exercise shows that.

Field notes

  • Write the playbook for the actions that you can really take. A step such as "revoke the key" needs a key that can be revoked and a person who may do it, so check that before the night.
  • Keep the playbooks next to the detectors, in the same repository, so that a change to an alert id is reviewed together with its playbook. The checker can run in the build.
  • After each real incident, change the playbook: each step that took too long becomes a line in one of the five sections.
  • Practise as a tabletop. A playbook that nobody has used is a draft. Give a colleague the alert and the playbook, add one new fact every ten minutes (a second user, a key that cannot be revoked), and note the time of each step. Run one each quarter. Know your legal clocks: the GDPR gives 72 hours (Article 33), NIS2 asks for an early warning within 24 hours (Article 23), and the EU AI Act sets its own windows for serious incidents of high-risk systems (Article 73). Take the numbers from the text.