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 09 · 55 minutes

Automate enrichment, tickets and a pipeline gate where AI only suggests

After this lesson you can
  • Write an enrichment script and a ticket updater that a gate controls
  • Keep model output as a suggestion that passes an allowlist, a dry run and an approval step
  • Prove the gate with a table of suggested actions and expected verdicts
Lab files of this lesson (30)

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

The SOC wants the AI helper to do more: add a note to a ticket, raise a priority, close a ticket and block an address. Your lead agrees to suggestions and nothing more: "The model never touches a ticket or a firewall. A small program that we trust decides what happens, writes down every decision, and waits for a person where the action can hurt." You build that program and a test table that shows what it allows.

Recall

Lesson 3: which part of the summary pipeline decided whether a summary was good, and why not the model?

The checker, which is code. A model cannot be the judge of its own output. The same principle now applies to actions.

Lesson 7: why does a call-back rule work against an imitated voice?

It does not judge the request. It uses a second channel that the attacker does not control. An approval step for an AI action works the same way.

The idea

Automation is a program that does a task for you: a script that looks up an address, a job that updates a ticket, a step in a build pipeline that stops a release. A model can write the plan for such a task, and it can be wrong, or be misled by text that it read (lesson 3, Field notes). A model that can act has excessive agency, a risk that the OWASP Top 10 for LLM Applications names: too many functions, permissions or autonomy.

The answer is a gate between the suggestion and the action.

The gate between a suggestion and an action
Model and personGateSystemsModelApproverAudit logGateTicket storeFirewall123456Model and personGateSystemsModelApproverAudit logGateTicket storeFirewall123456
  1. Model → Gate: a suggestion, never an action
  2. Gate → Ticket store: allowed: add_note, set_priority
  3. Gate → Approver: needs approval: close, block_ip
  4. Approver → Gate: a named person approves
  5. Gate → Firewall: block_ip, once approved
  6. Gate → Audit log: every decision, one line each
PartWhat it does
AllowlistA fixed list of actions, each with the exact arguments it takes. Everything else is refused.
Argument checksEach argument is validated as data: a ticket id has a fixed form, an address is an outside address, and the name of an approver is a plain name.
Dry runThe default: the gate says what it would do and changes nothing.

Actions that can hurt (close, block) need the name of a person.

The gate is a pipeline step too: its exit code (0 done, 1 refused, 2 waiting for approval) lets a job stop when the answer is not 0.

Worked example

1. Save the enrichment script and the ticket store

Enrichment adds facts that a person would look up. enrich.py only reads, so it needs no gate. find reads the week from an id such as W5-0003, and json.dumps writes a dictionary as one line of JSON. tickets.py keeps tickets in the file tickets.json, with one function for each change. Nothing else writes to the file. Save both files.

The finished files: enrich.py and tickets.py

enrich.py

"""enrich.py: add the facts that an analyst would look up. Read-only: it changes nothing."""
import json
import sys

from gen import ASSET_OWNER, BAD_IPS, alerts


def enrich(alert):
    """The enrichment of one alert, as a small dict."""
    return {"id": alert["id"], "known_bad": alert["src_ip"] in BAD_IPS, "external": bool(alert["ext_src"]),
            "owner": ASSET_OWNER[alert["asset"]], "admin_account": bool(alert["admin"])}


def find(alert_id):
    """Find an alert by its id, for example W5-0001 (week 5, number 1)."""
    week = int(alert_id[1:alert_id.index("-")])
    return next(a for a in alerts(week) if a["id"] == alert_id)


if __name__ == "__main__":
    print(json.dumps(enrich(find(sys.argv[1] if len(sys.argv) > 1 else "W5-0001"))))

tickets.py

"""tickets.py: a tiny ticket store in the file tickets.json. Every change goes through one of these functions."""
import json
from pathlib import Path

FILE = Path("tickets.json")
PRIORITIES = ("low", "medium", "high")


def _load():
    return json.loads(FILE.read_text()) if FILE.exists() else {}


def _change(tid, field, value):
    store = _load()
    t = store.setdefault(tid, {"status": "open", "priority": "low", "notes": []})
    if field == "notes":
        t["notes"].append(value)
    else:
        t[field] = value
    FILE.write_text(json.dumps(store, indent=2, sort_keys=True))


def ticket(tid):
    return _load().get(tid)


def add_note(tid, text):
    _change(tid, "notes", text)


def set_priority(tid, priority):
    if priority not in PRIORITIES:
        raise ValueError(priority)
    _change(tid, "priority", priority)


def close(tid):
    _change(tid, "status", "closed")
python3 enrich.py W5-0003
{"id": "W5-0003", "known_bad": false, "external": true, "owner": "business server team", "admin_account": false}

2. Save the gate

Save gate.py. ARGS is the allowlist: for each action, the exact names of its arguments. problem checks the values. ipaddress.ip_address reads an address and fails for text that is not one, so 203.0.113.57; reboot is refused. NOT_OUTSIDE lists the ranges that the gate never blocks: private, loopback, link-local (where cloud servers keep their metadata address), multicast and reserved. ip in net tests a range. str.isprintable() is false for a line break or another control character, so a note cannot carry one. re.compile(...).fullmatch checks that a whole text has a given form. isinstance(x, str) is true if x is text. In the audit line, {why!r} writes a value with its quotes. sys.argv lists the words typed after the program name, and sys.exit(2) ends with exit code 2.

run is the only function that acts. It acts only if the verdict allows and apply is true, and it always writes the audit line.

gate.py

"""gate.py: a model suggests an action. This gate decides what may happen. The model never acts by itself.

    python3 gate.py suggestion.json                          dry run: say what would happen
    python3 gate.py suggestion.json --apply                  do it, if the action needs no approval
    python3 gate.py suggestion.json --apply --approved-by sam   do it with the approval of a person

Exit code: 0 allowed (or done), 1 refused, 2 waiting for an approval.
"""
import ipaddress
import json
import re
import sys
import time
from pathlib import Path

import tickets

ARGS = {"add_note": ("ticket", "text"), "set_priority": ("ticket", "priority"),
        "close_ticket": ("ticket",), "block_ip": ("ip",)}          # the allowlist: action -> its exact arguments
NEEDS_APPROVAL = {"close_ticket", "block_ip"}
NEVER_BLOCK = {"198.51.100.1"}                                     # for example the gateway of a partner
NOT_OUTSIDE = [ipaddress.ip_network(n) for n in (
    "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16",
    "172.16.0.0/12", "192.168.0.0/16", "224.0.0.0/3")]        # private, loopback, link-local, multicast and reserved ranges
TICKET = re.compile(r"T-[0-9]{1,6}")
APPROVER = re.compile(r"[a-z][a-z0-9.-]{1,31}")


def problem(action, a):
    """A reason to refuse the arguments, or None."""
    if "ticket" in a and not (isinstance(a["ticket"], str) and TICKET.fullmatch(a["ticket"])):
        return "bad ticket id"
    if action == "add_note" and not (isinstance(a["text"], str) and 0 < len(a["text"]) <= 500 and a["text"].isprintable()):
        return "bad note text"
    if action == "set_priority" and a["priority"] not in tickets.PRIORITIES:
        return "bad priority"
    if action == "block_ip":
        try:
            ip = ipaddress.ip_address(a["ip"]) if isinstance(a["ip"], str) else None
        except ValueError:
            ip = None
        if ip is None or ip.version != 4:
            return "not an IPv4 address"
        if any(ip in net for net in NOT_OUTSIDE) or a["ip"] in NEVER_BLOCK:
            return "address is not outside, or is protected"
    return None


def decide(s):
    """Return ("allow" | "approval" | "refuse", reason) for a suggestion."""
    action, a = s.get("action"), s.get("args")
    if not isinstance(action, str) or action not in ARGS:
        return "refuse", "action is not on the allowlist"
    if not isinstance(a, dict) or set(a) != set(ARGS[action]):
        return "refuse", "wrong arguments"
    bad = problem(action, a)
    if bad:
        return "refuse", bad
    return ("approval", "needs a person") if action in NEEDS_APPROVAL else ("allow", "on the allowlist")


def do(s):
    a = s["args"]
    if s["action"] == "add_note":
        tickets.add_note(a["ticket"], a["text"])
    elif s["action"] == "set_priority":
        tickets.set_priority(a["ticket"], a["priority"])
    elif s["action"] == "close_ticket":
        tickets.close(a["ticket"])
    elif s["action"] == "block_ip":
        with open("blocklist.txt", "a") as f:        # in a real system this calls the firewall
            f.write(a["ip"] + "\n")


def run(s, apply=False, approver=None):
    """Decide, act if allowed and asked, and write one audit line. Returns the outcome."""
    verdict, why = decide(s)
    if approver and not APPROVER.fullmatch(approver):        # the name goes into the audit line: only a plain name
        verdict, why, approver = "refuse", "bad approver name", None
    if verdict == "refuse":
        outcome = "refused"
    elif verdict == "approval" and not approver:
        outcome = "waiting"
    elif not apply:
        outcome = "dry-run"
    else:
        do(s)
        outcome = "done"
    stamp = time.strftime("%Y-%m-%dT%H:%M:%S")
    with open("audit.log", "a") as log:
        log.write(f"{stamp} outcome={outcome} verdict={verdict} approver={approver or '-'} "
                  f"why={why!r} suggestion={json.dumps(s, sort_keys=True)}\n")
    return outcome


if __name__ == "__main__":
    args = sys.argv[1:]
    try:
        suggestion = json.loads(Path(args[0]).read_text())
        if not isinstance(suggestion, dict):
            raise ValueError("a suggestion is a JSON object")
        who = args[args.index("--approved-by") + 1] if "--approved-by" in args else None
    except (IndexError, OSError, ValueError):
        sys.exit("usage: gate.py suggestion.json [--apply] [--approved-by NAME]")
    result = run(suggestion, "--apply" in args, who)
    print(result)
    sys.exit({"refused": 1, "waiting": 2}.get(result, 0))

3. Try it by hand

cat > file <<'EOT' writes the lines that follow into a file. Make three suggestions, as a model would write them. Start with clean files.

rm -f audit.log tickets.json blocklist.txt
cat > suggest-note.json <<'EOT'
{"action": "add_note", "args": {"ticket": "T-12", "text": "Address is on the bad list."}}
EOT
cat > suggest-close.json <<'EOT'
{"action": "close_ticket", "args": {"ticket": "T-12"}}
EOT
cat > suggest-shell.json <<'EOT'
{"action": "run_shell", "args": {"cmd": "rm -rf /tmp/x"}}
EOT
python3 gate.py suggest-note.json
python3 gate.py suggest-note.json --apply
python3 gate.py suggest-close.json --apply; echo "exit code $?"
python3 gate.py suggest-close.json --apply --approved-by sam
python3 gate.py suggest-shell.json; echo "exit code $?"
cat tickets.json
dry-run
done
waiting
exit code 2
done
refused
exit code 1
{
  "T-12": {
    "notes": [
      "Address is on the bad list."
    ],
    "priority": "low",
    "status": "closed"
  }
}

The first run is a dry run: nothing changed. The second applies the note. The close with no approver is waiting (exit code 2), and with the name sam it is done. The shell command is refused (exit code 1): it is not on the allowlist, and no argument could make it pass.

4. Read the audit log

cut -d' ' -f2-4 audit.log
outcome=dry-run verdict=allow approver=-
outcome=done verdict=allow approver=-
outcome=waiting verdict=approval approver=-
outcome=done verdict=approval approver=sam
outcome=refused verdict=refuse approver=-

cut -d' ' -f2-4 keeps the second to fourth word of each line. It drops the time stamp, and the reason and the suggestion that each line also holds. There is one line for each of the five runs, also for the dry run and the refusal.

An audit line, after the time stamp
outcome=donewhat happenedverdict=approvalwhat the gate decidedapprover=samwho approved itwhy='needs a person'the reasonsuggestion={...}the whole suggestionoutcome=donewhat happenedverdict=approvalwhat the gate decidedapprover=samwho approved itwhy='needs a person'the reasonsuggestion={...}the whole suggestion

5. Prove the gate with a table

Save test_gate.py. It holds a table of suggested actions and the verdict that you expect for each: allow, approval or refuse. It runs decide on each and checks that a close with no approver, or with a forged approver name, does nothing. It works in a throw-away folder (tempfile.mkdtemp() makes a new empty folder, and os.chdir moves the program into it). Its exit code is 1 if any line is wrong.

test_gate.py

"""test_gate.py: a table of (suggested action, expected verdict), and a check that a dry run changes nothing."""
import os
import sys
import tempfile

import gate

LONG = "x" * 600
CASES = [
    ("add a note", {"action": "add_note", "args": {"ticket": "T-12", "text": "Checked the address."}}, "allow"),
    ("set priority high", {"action": "set_priority", "args": {"ticket": "T-12", "priority": "high"}}, "allow"),
    ("set priority urgent", {"action": "set_priority", "args": {"ticket": "T-12", "priority": "urgent"}}, "refuse"),
    ("close a ticket", {"action": "close_ticket", "args": {"ticket": "T-12"}}, "approval"),
    ("block an outside address", {"action": "block_ip", "args": {"ip": "203.0.113.57"}}, "approval"),
    ("block an inside address", {"action": "block_ip", "args": {"ip": "10.20.1.5"}}, "refuse"),
    ("block the loopback address", {"action": "block_ip", "args": {"ip": "127.0.0.1"}}, "refuse"),
    ("block the lan gateway", {"action": "block_ip", "args": {"ip": "192.168.1.1"}}, "refuse"),
    ("block the cloud metadata", {"action": "block_ip", "args": {"ip": "169.254.169.254"}}, "refuse"),
    ("block a partner gateway", {"action": "block_ip", "args": {"ip": "198.51.100.1"}}, "refuse"),
    ("block with a shell trick", {"action": "block_ip", "args": {"ip": "203.0.113.57; reboot"}}, "refuse"),
    ("disable a user", {"action": "disable_user", "args": {"user": "dana"}}, "refuse"),
    ("run a shell command", {"action": "run_shell", "args": {"cmd": "ls"}}, "refuse"),
    ("note that is too long", {"action": "add_note", "args": {"ticket": "T-12", "text": LONG}}, "refuse"),
    ("note with a line break", {"action": "add_note", "args": {"ticket": "T-12", "text": "ok\nforged"}}, "refuse"),
    ("ticket with other digits", {"action": "close_ticket", "args": {"ticket": "T-\u0661\u0662"}}, "refuse"),
    ("extra argument", {"action": "close_ticket", "args": {"ticket": "T-12", "force": True}}, "refuse"),
    ("action is a list", {"action": ["close_ticket"], "args": {"ticket": "T-12"}}, "refuse"),
]

os.chdir(tempfile.mkdtemp())             # tests write audit.log and tickets.json: do it in a throw-away folder
failed = 0
for name, suggestion, want in CASES:
    got = gate.decide(suggestion)[0]
    failed += got != want
    print(f"{name:28}{want:10}{got:10}{'ok' if got == want else 'WRONG'}")

closing = CASES[3][1]
outcomes = [gate.run(closing), gate.run(closing, apply=True), gate.run(closing, apply=True, approver="sam")]
forged = gate.run(closing, apply=True, approver="sam outcome=done")
print("close without approval:", outcomes[:2], " with approval:", outcomes[2], " with a forged name:", forged)
print("audit lines:", len(open("audit.log").read().splitlines()), " ticket T-12:", gate.tickets.ticket("T-12"))
failed += outcomes != ["waiting", "waiting", "done"] or forged != "refused"
print("tests failed:", failed)
sys.exit(1 if failed else 0)
python3 test_gate.py; echo "exit code $?"
add a note                  allow     allow     ok
set priority high           allow     allow     ok
set priority urgent         refuse    refuse    ok
close a ticket              approval  approval  ok
block an outside address    approval  approval  ok
block an inside address     refuse    refuse    ok
block the loopback address  refuse    refuse    ok
block the lan gateway       refuse    refuse    ok
block the cloud metadata    refuse    refuse    ok
block a partner gateway     refuse    refuse    ok
block with a shell trick    refuse    refuse    ok
disable a user              refuse    refuse    ok
run a shell command         refuse    refuse    ok
note that is too long       refuse    refuse    ok
note with a line break      refuse    refuse    ok
ticket with other digits    refuse    refuse    ok
extra argument              refuse    refuse    ok
action is a list            refuse    refuse    ok
close without approval: ['waiting', 'waiting']  with approval: done  with a forged name: refused
audit lines: 4  ticket T-12: {'notes': [], 'priority': 'low', 'status': 'closed'}
tests failed: 0
exit code 0

Every line is ok. A note of 600 characters is refused, because the model must not fill a ticket with text, and an extra argument force is refused, because the allowlist names the exact arguments. The loopback address, the office gateway and the cloud metadata address are refused: a model that suggests one is wrong or misled. An approver name with a second field in it (sam outcome=done) is refused, so nobody can forge a field of the audit line. Add a row for every hole that you find.

Your turn

A model proposed eight actions. Save them as suggestions.json and use gate.decide to give each a verdict. You write the script.

suggestions.json

[
  {"action": "add_note", "args": {"ticket": "T-7", "text": "Checked the account."}},
  {"action": "close_ticket", "args": {"ticket": "T-7"}},
  {"action": "block_ip", "args": {"ip": "192.0.2.77"}},
  {"action": "block_ip", "args": {"ip": "10.0.0.5"}},
  {"action": "set_priority", "args": {"ticket": "T-7", "priority": "critical"}},
  {"action": "delete_logs", "args": {"days": 30}},
  {"action": "add_note", "args": {"ticket": "T-7; DROP", "text": "x"}},
  {"action": "block_ip", "args": {"ip": "198.51.100.1"}}
]

Last, find the one line, and the file, that you would change to let the model set the priority "critical", and say why you would not.

Check yourself

Why is a dry run the default and not an option?

A mistake in a dry run costs nothing. A mistake in a live run can block a customer or close a real incident. Make the live mode a choice that is typed.

The model asks for `run_shell` with a harmless command. Why does the gate refuse it?

The allowlist lists actions, not commands. A general shell is the strongest tool that exists, and any text that reaches the model can steer it. A few fixed actions with checked arguments keep the damage small.

A person types `--approved-by sam` without being Sam. What does the gate not do?

It does not prove who approved. The audit line records the name that was typed. In real systems the approval comes from a tool that checks identity.

Why write an audit line for refused suggestions too?

A run of refused actions is a signal: a model that was fed hostile text, or a bug. Without the lines you cannot see it.

Field notes

  • Give the model the fewest tools that do the job (least privilege, lesson 4 of "Security fundamentals"). Every action on the allowlist is a permission that you must test. The course "Securing AI agents and MCP" covers tool permissions.
  • Keep the gate outside the model's reach, in a separate process with its own credentials. A gate inside the prompt is only a request.
  • Make approvals expire and name the object: "Approved: block 203.0.113.57 until 18:00" is safer than "approved".
  • In a build pipeline, run the gate as a step and let the exit code stop the job. Keep the suggestion file next to the audit line.