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

Check an AI review and control the AI helpers

After this lesson you can
  • Check each finding of an AI review against the code and count the true, the invented and the missed
  • Say what each kind of AI helper reads and sends, and what can go wrong
  • Check a list of installed helpers against an allowlist of names, versions and sites
Lab files of this lesson (45)

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 AI review of the shop program has arrived. Your lead has two questions. Which of its findings are true? And the developers want plug-ins and assistants: which may they install, and what do they send away? You answer the first on the code of lesson 10, and the second on a list of what is installed on the developers' machines.

Recall

Lesson 10: which checks are the gate, and why is an AI review not one of them?

The linter, the composition scan, the tests and the model test, each with an exit code. A review can invent a fault and miss one, and it gives no rule to explain why. It stays a lead.

Lesson 9: what does the gate do with an action that is not on its allowlist?

It refuses the action, whatever the model says. An allowlist names what is allowed, and everything else is refused.

The idea

For each AI helper, ask what it reads, what it sends and what a person must check. An allowlist is the list of helpers, versions and sites that the company has approved. The gate of lesson 9 used one for actions, and here it is for software. Anything else is blocked.

HelperCan readCan send or doWhat can go wrong
IDE plug-inThe project's filesCode to the vendor, editsSource and secrets leave
Browser plug-inEvery page, including formsPage text to a serviceIt sees customer data and consoles
CLI plug-inHistory, files, environmentCommands that it runsA key in the environment leaves
Personal assistantMail, calendar, filesMessages in your nameA prompt in a mail can steer it
Low-code or no-code toolWhatever its connectors reachActions in many systemsA flow is a program with no review

A low-code tool builds a flow from blocks with a little code, and a no-code tool does it with none. Treat such a flow like a script of lesson 9: approved connectors, a named owner, an approval step, a log.

An entry on the allowlist is more than a name. A new version can change what a helper reads, and an update can send data to a new host. So the list holds the versions and the sites that a person approved.

An IDE plug-in between files and vendor
Your computerVendorDeveloperIDE plug-inProject filesKey fileVendor service1234Your computerVendorDeveloperIDEplug-inProjectfilesKey fileVendor service1234
  1. Developer → IDE plug-in: asks for a review
  2. IDE plug-in → Project files: reads the open files
  3. IDE plug-in → Key file (blocked): on the exclude list, not read
  4. IDE plug-in → Vendor service: sends the code to be reviewed

Worked example

1. Save the faulty program and the AI review

Lesson 10 has you fix shop/app.py, so this lesson uses its own copy of the faulty original. Save it as drafts/app-faulty.py. Nobody edits this file. mkdir -p makes the folder, and does nothing if you made it in lesson 10.

mkdir -p drafts

drafts/app-faulty.py

"""app.py: the order lookup of the Harbourline shop (a colleague's draft)."""
import os
import sqlite3

LABEL_KEY = "kr-demo-9f3a7c1d52"      # key of the label printer service (invented)


def connect():
    db = sqlite3.connect(":memory:")
    db.execute("create table orders (id text, customer text, total real)")
    db.execute("insert into orders values ('A1', 'alma', 12.5), ('B2', 'boris', 80.0)")
    return db


def find_order(db, order_id):
    return db.execute(f"select id, customer, total from orders where id = '{order_id}'").fetchall()


def label_headers():
    return {"Authorization": "Bearer " + LABEL_KEY}

ai-review-stub.json is a stub, a stand-in with fixed text. The course wrote it for this lab, and a model did not, so it is not recorded model output like recorded-03.json of lesson 3. It has the shapes of a real review: a true finding, a finding about code that is not there, and a fault that it never mentions. Each claim has a line, a quote of the code and the claim itself.

ai-review-stub.json

[
  {"line": 16, "quote": "where id = '{order_id}'",
   "claim": "The order id is put into the SQL text. An id with a quote can change the query: SQL injection."},
  {"line": 20, "quote": "os.system(",
   "claim": "label_headers runs a shell command with os.system and a value from the caller: command injection."}
]

2. Check each claim of an AI review against the code

One claim of the AI review
line 20where it says the fault isos.system(the code that it quotesruns a shell command: command injectionwhat it claimsline 20where it says the fault isos.system(the code that it quotesruns a shell command: command injectionwhat it claims

The second claim says that label_headers calls os.system. Search drafts/app-faulty.py: it is not there. Save verify.py to check every claim, and to list what the linter of lesson 10 found that the review did not mention. {... for ... in ...} builds a set, each line once, and flagged - cited is the lines that are in the first set and not in the second.

verify.py

"""verify.py: check each claim of an AI review against the code."""
import json
import sys

from lint import scan

path, review = sys.argv[1], json.load(open(sys.argv[2]))
lines = open(path).read().splitlines()
flagged = {line for line, kind, _ in scan(path) if kind == "security"}
cited = {claim["line"] for claim in review}
true = 0
for claim in review:
    where = [n for n, text in enumerate(lines, 1) if claim["quote"] in text]
    found = claim["line"] in where
    true += found
    verdict = "the quote is there" + (" and the linter flags it" if claim["line"] in flagged else "") if found else "no such code on that line"
    print(f"claim about line {claim['line']}: {verdict}")
missed = sorted(flagged - cited)
for line in missed:
    print(f"the linter flags line {line}, and the review did not mention it")
print(f"true {true}, invented {len(review) - true}, missed by the review {len(missed)}")
python3 verify.py drafts/app-faulty.py ai-review-stub.json
claim about line 16: the quote is there and the linter flags it
claim about line 20: no such code on that line
the linter flags line 5, and the review did not mention it
true 1, invented 1, missed by the review 1

One finding is true and the linter agrees. One is invented. The secret in line 5 is missed, and so is the dependency fault of lesson 10, which the review could not see and the program cannot count. The mix is the course's, so count your own on a real review.

3. Check the installed helpers against the allowlist

installed.json is what an inventory of the developers' machines might report: for each helper its kind, its version and the site that it sends to. All names are invented. allowlist.json holds what the company approved.

installed.json

[
  {"name": "kr-complete", "kind": "IDE plug-in", "version": "2.1.0", "site": "api.kr-complete.example"},
  {"name": "kr-pagesum", "kind": "browser plug-in", "version": "1.4.2", "site": "sum.kr-pagesum.example"},
  {"name": "kr-shell-ai", "kind": "CLI plug-in", "version": "0.9.0", "site": "api.kr-shell.example"},
  {"name": "kr-flowbot", "kind": "low-code tool", "version": "3.0.1", "site": "flows.kr-flowbot.example"},
  {"name": "kr-mailpal", "kind": "personal assistant", "version": "1.0.0", "site": "api.kr-mailpal.example"}
]

allowlist.json

[
  {"name": "kr-complete", "versions": ["2.1.0", "2.1.1"], "sites": ["api.kr-complete.example"]},
  {"name": "kr-pagesum", "versions": ["1.3.0"], "sites": ["sum.kr-pagesum.example"]},
  {"name": "kr-flowbot", "versions": ["3.0.1"], "sites": ["flows.kr-flowbot.example"]}
]

Save helpers.py. It turns the allowlist into a dict by name (allowed.get gives None for a name that is not there), and then checks the name, the version and the site, in that order. It ends with exit code 1 if any helper is blocked.

helpers.py

"""helpers.py: check the installed AI helpers against the allowlist. Exit code 1 if one is not allowed."""
import json
import sys

installed = json.load(open(sys.argv[1]))
allowed = {entry["name"]: entry for entry in json.load(open(sys.argv[2]))}
blocked = 0
for h in installed:
    rule = allowed.get(h["name"])
    if rule is None:
        problem = "NOT on the allowlist"
    elif h["version"] not in rule["versions"]:
        problem = f"version {h['version']} is not approved (approved: {', '.join(rule['versions'])})"
    elif h["site"] not in rule["sites"]:
        problem = f"sends to {h['site']}, which is not approved"
    else:
        problem = ""
    print(f"{h['name']:13}{h['kind']:20}{problem or 'allowed'}")
    if problem:
        blocked += 1
print("blocked:", blocked, "of", len(installed))
sys.exit(1 if blocked else 0)
python3 helpers.py installed.json allowlist.json; echo "exit code $?"
kr-complete  IDE plug-in         allowed
kr-pagesum   browser plug-in     version 1.4.2 is not approved (approved: 1.3.0)
kr-shell-ai  CLI plug-in         NOT on the allowlist
kr-flowbot   low-code tool       allowed
kr-mailpal   personal assistant  NOT on the allowlist
blocked: 3 of 5
exit code 1

Two helpers are allowed. The browser plug-in was updated past the approved version, so it is blocked until a person has read what 1.4.2 changed. The CLI plug-in reads the environment, and the assistant reads mail: neither has been approved. A low-code flow is on the list with one version and one site. The list does not replace a person. It makes the approval a record that a program can check on every machine.

Your turn

Use the files of this lesson. You write the changes.

  1. Add a third claim to a copy of the review: line 5, quote LABEL_KEY =, claim "a key is written in the code". Run verify.py on it.
  2. Assume that a person has read the vendor's notes for 1.4.2 of kr-pagesum and approved it: add that version to allowlist.json. Add kr-shell-ai, version 0.9.0, site api.kr-shell.example. Run helpers.py.
  3. In installed.json, change the site of kr-complete to telemetry.kr-complete.example, as an update might. Run helpers.py again.

Last, write two sentences on why you left kr-mailpal blocked, and what you would ask its vendor. The page does not check this.

Check yourself

The review in this lesson invented a fault and missed two. Is it useless?

No. One finding was true. But a review stays a lead: verify each claim against the code, count the true, the invented and the missed, and let a scanner and a test be the gate. The program counts one miss, the secret. The other is the dependency fault. The course wrote this mix, and a real review gives another.

A team installs a browser plug-in that summarises every page. What do you ask first?

What it reads and where it sends it. On an admin console or a customer record, the text leaves the company. The answer decides whether, for whom and on which sites it is on the allowlist.

A team builds a flow in a no-code tool that reads the help desk and closes tickets. What must it have before it goes live?

The same as a script of lesson 9: connectors that someone approved, a named owner, an approval step for an action that changes something, and a log. A flow that no one reviews is a program that no one reviews.

An approved plug-in updates, and the version number is the same. What does the allowlist check miss?

A change that the version does not show, such as a new site. So the list also holds the site, and a hash of the file is a stronger key where the vendor publishes one.

Field notes

  • To see a real review, send the faulty program to your model with chat of llm.py (lesson 3). This needs the model server, and this lesson does not check it. Count the true, the invented and the missed, as in step 2.
python3 -c "
from llm import chat
print(chat([{'role': 'user', 'content': 'Name the line of each security fault:\n' + open('drafts/app-faulty.py').read()}], max_tokens=300))
"
  • Exclude files with secrets from a plug-in, and rotate any key that was in a prompt.
  • Build the inventory from the machines themselves (a package list, the browser's policy file), and run the check on a schedule: a helper that someone installs on Tuesday is on no list on Monday.
  • Take the vendor's terms on data use and retention into the approval, and write down who approved which version.