Advanced / Detection and incident response for AI
Detection and incident response for AI cheat sheet
Set up the lab (lesson 0)
| Task | Command or code |
|---|---|
| Make the lab folder | mkdir -p ~/krlab/ai-detection-response |
| Build the lab from the zip as it stands after a lesson | sh kr-lab.sh LESSON_FOLDER ~/krlab/ai-detection-response (run it in the unzipped folder; the folder has the name of the lesson file without .md) |
| Write the data, or reset the state | python3 makelogs.py |
| Prove that the lab works | python3 labcheck.py (last line lab ready: 6 of 6) |
| Look at the first record | head -n 1 logs/week1.jsonl |
Decide what to log (lesson 1)
| Task | Command or code |
|---|---|
| Fields of a record | id ts user prompt_sha prompt_len excerpt resp_len model tools docs decision tokens_in tokens_out cost confidence |
| Mask secrets before cutting | sanitise(text)[:60] |
| Make a record without text | make_record(rid, ts, event) |
| List why a record must not be logged | violations(record) |
| Append a record, or refuse it | write(path, record) |
| Apply retention | retain(record, now, held=False) (excerpt 7 days, record 90, hold 365). Run the detectors that read the excerpt within 7 days |
| Run the tests | python3 test_logrec.py |
| Take away the write right, show the mode | chmod 440 FILE, stat -c '%a %n' FILE |
| Seal a closed log, then check it | sha256sum FILE > FILE.sha256, sha256sum -c FILE.sha256 (exit code 1 when changed) |
Detect injection and abuse (lesson 2)
| Task | Command or code |
|---|---|
| Count each rule on both weeks | python3 run_detect.py |
| Score of a record | phrase 1, long text 1, tool after an ext- document 2; alert at 2 |
| Users with many refusals in a day | detect.refusal_alerts(records) |
| Narrow the tool rule | NARROW = {"issue_refund", "send_email_external"} |
Watch drift and quality (lesson 3)
| Task | Command or code |
|---|---|
| Confidence from log-probabilities | math.exp(sum(logprobs) / len(logprobs)) |
| Day-by-day drift against a baseline | python3 run_drift.py |
| Population stability index | drift.psi(baseline, new); drift above 0.2, at least 100 answers |
| Answers for people to read | drift.review_queue(records) (below 0.5, plus 1 in 20 by hash of the id) |
| Share records without naming anyone | Drop id, user, prompt_sha, excerpt, docs, model, cost, tokens and lengths; use the day and int(confidence * 10) / 10; remove groups under 5 records (lesson 3, step 6) |
| Count equal records, test the smallest group | Counter(rows), min(size.values()) over ALL released columns (k-anonymity, k = 5) |
| Check that pseudonyms can be undone | Hash guessed names with pseudonym(), count the users found again (58 of 62) |
Watch rate and cost (lesson 4)
| Task | Command or code |
|---|---|
| Cost report and alerts | python3 run_cost.py |
| Cost of a request | tokens_in * 3e-6 + tokens_out * 15e-6 (invented prices) |
| Robust z-score | 0.6745 * (x - median) / MAD; look above 3.5 |
| Users over the hourly limit | cost.user_hour_alerts(records) (more than 30) |
| Top users by cost | cost.top_users(records) |
| Four parts of the cost | prompts, responses, processing (tool calls, documents), storage (lesson 4, step 6) |
Spot extraction (lesson 5)
| Task | Command or code |
|---|---|
| Features of each user | extract.features(records) |
| Table of precision and recall | python3 run_extract.py |
| Precision, recall | right ÷ found, right ÷ real |
| Flag with the allow-list | extract.flagged(feats, extract.RULES["+ not on allow-list"]) |
Write playbooks (lesson 6)
| Task | Command or code |
|---|---|
| Alert ids | A-INJ, A-REFUSE, A-DRIFT, A-RATE, A-COST, A-EXTRACT, A-LOG-SECRET, A-LEAK |
| Five sections of a playbook | ### Trigger, ### First actions, ### Owner, ### Evidence, ### Communication |
| Check a folder of playbooks | python3 check_playbooks.py playbooks |
| Read the exit code | echo "exit code $?" (1 for a problem or an empty folder) |
Contain, roll back, recover (lesson 7)
| Task | Command or code |
|---|---|
| Disable, enable a tool | python3 respond.py disable-tool send_email_external, python3 respond.py enable-tool send_email_external |
| Revoke a key | python3 respond.py revoke-key key-mail-gateway |
| Safe mode on, off | python3 respond.py safe-mode on, python3 respond.py safe-mode off |
| Pause, resume ingestion | python3 respond.py pause-ingest, python3 respond.py resume-ingest |
| Limit a user (requests a day, 0 blocks) | python3 respond.py limit-user u_3ca43ca6 30 |
| Roll back to a known-good version | python3 respond.py rollback model orbi-1.2, python3 respond.py rollback index kb-v6 |
| Verify with the test set | python3 respond.py verify (passes at 90 percent) |
| Read the change record | state/changes.jsonl |
Audit (lesson 8)
| Task | Command or code |
|---|---|
| Run all four audits | python3 audit.py |
| Interval for a share | audit.wilson(correct, total) |
| Ratio of outcomes between groups | lower rate ÷ higher rate; look below 0.8 |
| Tool uses outside the role, permissions that the role never used | audit.access_audit(records, access) |
Build and run the kit (lessons 9 and 10)
| Task | Command or code |
|---|---|
| Run everything on week 2 | python3 kit.py (the first column is the alert id that picks the playbook) |
| Run on another week | python3 kit.py logs/week1.jsonl |
| What makes the kit exit 1 | A secret in the log, a playbook with a problem, or a folder with no playbook (not alerts) |
| Make the scenario week | python3 scenario_week.py |
| Fingerprint of a file | sha256sum logs/week3.jsonl | cut -c1-12 |
Safety habits
- Log the shape of an interaction, not its text. Mask secrets first, then cut. Give every field a time limit.
- Treat a pseudonym as personal data. Keep the salt away from the log store. Share only anonymised records.
- Give the log its own owner, read access to a group, and a stored digest of every closed log.
- The excerpt lives 7 days. Run the detectors in that time and keep their results, not the excerpt.
- Read every alert before you trust a count. A quiet week is the best test of a rule.
- Use the median and not the mean to find a spike, and compare like with like.
- State the threshold and the sample size next to every result. A small sample gives a wide range.
- Contain with the smallest action that stops the harm. Record each change with its old value.
- Roll back only to a version that was tested, and call the recovery done only when the test set passes.
- Keep the evidence under hold, and tell only the people the playbook names.
- Say what an audit cannot show, in the audit record.