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 02 · 40 minutes

Inventory your AI systems and find the shadow ones

After this lesson you can
  • Keep an AI inventory as a checked CSV file
  • Find AI use that is not in the inventory by running a rule over records
  • Report the counts and the limits of what the rule can prove
Lab files of this lesson (14)

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

Harbour Credit has an AI inventory with five entries. Finance tells your lead that the expense reports and the proxy logs show more AI products than that. "Staff sign up with a card and a browser, and nobody asks us." Your lead wants a list of AI use that is not in the inventory, with numbers, by tomorrow. You get 300 invented records: network records (the domain that a laptop contacted) and expense lines.

Recall

Lesson 1: why must each activity in a RACI table have exactly one A?

With zero, nobody answers for the activity. With two, each person can think the other one answers. One A gives one person to ask and one person to inform.

Lesson 1: what does a checker's exit code tell another program?

0 means that the checks passed and 1 means that at least one failed. A build job or a later script reads the number, not the text.

The idea

An inventory is a list of every AI system that the organisation builds, buys or uses, with an owner for each. You cannot govern, assess or test what you have not listed, so every later lesson starts here. Shadow AI is AI use that the organisation did not approve and did not list: a free chatbot in a browser, a plug-in, a tool paid on a personal card. It is a risk because nobody has checked where the data goes (lesson 9) or who answers for the result (lesson 1).

You find it from records that you already have. A rule over the records says what counts as AI use, and the inventory says what is known. The difference is the shadow list.

From records to a shadow list
Records you already haveMatchingResultNetwork recordsExpense linesAI ruleInventoryShadow list1234Records you already haveMatchingResultNetwork recordsExpense linesAI ruleInventoryShadow list1234
  1. Network records → AI rule: the domain that a laptop contacted
  2. Expense lines → AI rule: the product that somebody bought
  3. AI rule → Inventory: each AI use is matched to an entry
  4. Inventory → Shadow list: AI use with no entry

Two limits keep the result honest. A match shows that a laptop contacted a service or that somebody bought it. It does not show what data was sent. And a rule can match too much (a name that looks alike) or too little (a product that the rule does not know). Test the rule on names that look alike, as step 5 does. Treat every result as a lead for a conversation, not as proof of a breach.

Worked example

Work in ~/krlab/ai-governance with the environment on. This lesson imports govlib.py from lesson 1. Keep it in the same folder.

1. Save the inventory

The inventory has one row for each system. match holds the domain or product name that the system shows in the records, so that code can link a record to an entry. LoanScore, HelpBot and DocCheck are our own systems and have no match value.

One row of inventory.csv
S3idNova ChatnameDanaownerDrafts staff emailspurposeNovaChatvendorinternaldata_classnovachat.examplematch: the name that records showapprovedstatusS3idNova ChatnameDanaownerDrafts staff emailspurposeNovaChatvendorinternaldata_classnovachat.examplematch: the name that records showapprovedstatus

inventory.csv

id,name,owner,purpose,vendor,data_class,match,status
S1,LoanScore,Aino,Scores loan applications,in-house,personal,,approved
S2,HelpBot,Aino,Answers customer questions,ModelHost,personal,,approved
S3,Nova Chat,Dana,Drafts staff emails,NovaChat,internal,novachat.example,approved
S4,CodePal,Bram,Suggests code for engineers,CodePal Ltd,internal,CodePal,trial
S5,DocCheck,Chidi,Checks that application files are complete,in-house,personal,,approved

2. Save the rule as data

The rule is data, not code, so that a person without Python can add a product. A domain matches itself and its subdomains. A product name matches when it appears in a line of text as a whole word, in any case. All names and domains here are invented, and .example is a domain that cannot exist on the real internet.

ai_rules.json

{
  "domains": ["novachat.example", "lumina-ai.example", "pilotwrite.example", "deepgrove.example"],
  "products": ["SummarizeIt", "CodePal", "VoiceNote AI"]
}

3. Write the tool and check the inventory

json.load reads a JSON file into Python lists and dictionaries. Counter counts how often each value appears. str.endswith("." + domain) is true when a text ends with a dot and the domain, so chat.novachat.example matches and shop.mylumina-ai.example does not match lumina-ai.example. .lower() turns a text to lower case. re.search(pattern, text, re.I) looks for a pattern in a text and ignores case (re.I). In a pattern, \b marks the edge of a word, so \bCodePal\b matches CodePal Team and does not match CodePalace. re.escape(name) makes a name safe to use inside a pattern. {...!r} in an f-string shows a value with quotes. The command has two modes: check for the inventory file and shadow for the search.

inventory.py

"""inventory.py: check the AI inventory and find AI use that is not in it.

    python3 inventory.py check inventory.csv
    python3 inventory.py shadow inventory.csv data/records.csv ai_rules.json
"""
import csv
import json
import re
import sys
from collections import Counter

from govlib import finish

REQUIRED = ["id", "name", "owner", "purpose", "vendor", "data_class", "status"]
DATA_CLASSES = ["public", "internal", "personal"]
STATUSES = ["approved", "trial", "retired"]


def load(path):
    with open(path, newline="") as f:
        return list(csv.DictReader(f))


def problems(path):
    found, seen = [], set()
    for row in load(path):
        for field in REQUIRED:
            if not row[field].strip():
                found.append(f"{row['id']}: {field} is empty")
        if row["id"] in seen:
            found.append(f"{row['id']}: id used twice")
        seen.add(row["id"])
        if row["data_class"] not in DATA_CLASSES:
            found.append(f"{row['id']}: data_class {row['data_class']!r} is not one of {DATA_CLASSES}")
        if row["status"] not in STATUSES:
            found.append(f"{row['id']}: status {row['status']!r} is not one of {STATUSES}")
    return found


def matches(item, rules):
    """The rule entry that a record matches, or None. A domain matches itself and its subdomains."""
    low = item.lower()
    for domain in rules["domains"]:
        if low == domain or low.endswith("." + domain):
            return domain
    for product in rules["products"]:
        if re.search(r"\b" + re.escape(product) + r"\b", item, re.I):
            return product
    return None


def shadow(inventory_path, records_path, rules_path):
    """Return (records, AI records, unlisted AI records, unlisted AI use as {rule entry: count})."""
    with open(rules_path) as f:
        rules = json.load(f)
    listed = {row["match"] for row in load(inventory_path) if row["match"]}
    records = load(records_path)
    unlisted, ai = Counter(), 0
    for record in records:
        key = matches(record["item"], rules)
        if key:
            ai += 1
            if key not in listed:
                unlisted[key] += 1
    return len(records), ai, sum(unlisted.values()), unlisted


if __name__ == "__main__":
    if sys.argv[1] == "check":
        finish(problems(sys.argv[2]))
    total, ai, hidden, unlisted = shadow(*sys.argv[2:5])
    print(f"records {total}, AI use {ai}, listed {ai - hidden}, not in the inventory {hidden}")
    for key, count in unlisted.most_common():
        print(f"  {key.ljust(20)}{count}")
python inventory.py check inventory.csv
problems: 0

4. Find the shadow AI

Look at the first records, then run the search. head -4 prints the first four lines of a file.

head -4 data/records.csv
python inventory.py shadow inventory.csv data/records.csv ai_rules.json
id,source,team,item
R001,network,support,wiki.docnest.example
R002,network,engineering,models.deepgrove.example
R003,network,support,cal.planner.example
records 300, AI use 81, listed 26, not in the inventory 55
  pilotwrite.example  15
  deepgrove.example   14
  lumina-ai.example   10
  VoiceNote AI        9
  SummarizeIt         7
Of 300 records, the AI use
AI use81Listed in the inventory26Not in the inventory55AI use81Listed in the inventory26Not in the inventory55

Nova Chat and CodePal are listed. The five unlisted products or domains are the shadow list, and each one is a question for its team: who uses it, with which data, and who pays?

5. Test the rule against a look-alike

grep -c text file counts the lines that contain text. The generator added a decoy domain, shop.mylumina-ai.example, which is not an AI service. Products can have decoys too, so the second test runs matches on a look-alike product name, CodePalace, and on the real name. python -c runs the Python text that follows it.

grep -c "lumina-ai" data/records.csv
grep -c "api.lumina-ai.example" data/records.csv
33
10

33 lines hold the text lumina-ai, but the rule matched only 10 of them (the domain api.lumina-ai.example). A plain text search would have reported 23 false hits. The rule is stricter because it compares whole domain names.

python -c "import json; from inventory import matches; r = json.load(open('ai_rules.json')); print(matches('Team lunch, CodePalace', r)); print(matches('CodePal Team, monthly', r))"
None
CodePal

The look-alike gives None, and the real product gives its name. A plain substring test would have matched both. The rule compares whole words, but it still cannot know a product that is not in ai_rules.json: that is why somebody reviews the rules each month.

Your turn

The sales team agrees to register two tools: Lumina API (domain lumina-ai.example) and SummarizeIt (product SummarizeIt). Both are trial, with data class internal, and Gus owns both. Add them to inventory.csv as rows S6 and S7, and set match to lumina-ai.example and SummarizeIt. Then run the search again.

The sales lead also sent a file of tools that the team has listed. Save it and check it.

inventory-sales.csv

id,name,owner,purpose,vendor,data_class,match,status
T1,Pitch Writer,Gus,Drafts sales emails,PilotWrite,internal,pilotwrite.example,trial
T2,Call Notes,,Writes call summaries,VoiceNote,personal,VoiceNote AI,trial
T1,Lead Scorer,Hanne,Ranks sales leads,in-house,secret,,approved

Answer from your own runs. For the last two questions, write a few lines of Python that import inventory, use its matches function over data/records.csv, and count by the team column.

Last, write one sentence for your lead: what can this count tell them, and what can it not tell them?

Check yourself

Why is the AI rule kept in a JSON file and not in the code?

The people who learn about a new AI product are often not the people who write Python. A data file lets them add a line, and a reviewer can read the change in a diff. The code stays the same, so it needs no new test for each product.

A match for "CodePal" appears in an expense line. What does it prove, and what does it not prove?

It proves that somebody paid for something with that name. It does not prove that the tool sends company data, which data, or that the person is an employee of the team on the record. It is a lead for a question.

The rule has a product named "VoiceNote AI". Which risk does a short product name bring?

A short name can match unrelated lines (a name inside another word, as CodePalace holds CodePal). The result is false hits, and people stop trusting the report. The rule here matches whole words, and a look-alike product can still slip through with a different spelling. Test the rule on records that you know are not AI.

The report shows 55 unlisted records. Why is a rate of use a poor measure of risk?

A tool used once with customer data can hurt more than a tool used 50 times with public text. Count the records to find the leads, then rank the leads by the data class and by the owner's answer, and carry them into the risk register (lesson 3).

Field notes

  • Use more than one source. Proxy or DNS logs, expense lines, browser-extension lists and single sign-on records each see a different part. A tool that appears in two sources is a stronger lead.
  • Offer a short way to register a tool. If the approval takes weeks, staff will use the tool anyway. A short form and a fast answer give you a better inventory than a ban.
  • Store the inventory in version control, with the owner and a review date for each entry (lesson 8 shows the review dates). An inventory that nobody updates is a list of what was true last year.
  • Record the data class for each system. Lesson 9 uses it to decide where data may go, and lesson 6 uses the role and the purpose to classify the system.
  • Do not collect more than you need. A network record can show private browsing. Keep the rule narrow, keep the records for a limited time, and tell staff what you look at.