Lesson 10 · 60 minutes
Gate a change with scanners, tests and a pipeline
- Run a rule checker, a composition scan, tests and a model test on a program with planted faults
- Read the exit code of each check and say which fault it found
- Put the checks in a pipeline whose exit code is the gate
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
A colleague at Harbourline Logistics wrote a small order lookup, shop/app.py, and asked an AI assistant to review it before the merge. Your lead asks: "Can we merge on that review, or do we trust the build more?" You run the checks that a build runs on every change, and decide which of them is the gate. The next lesson puts the AI review beside them.
Recall
Lesson 9: what does the exit code of the gate let a pipeline do?
A job stops when a step does not end with 0. A suggestion is advice, and an exit code is a rule.
Lesson 2: why is the model measured on week 5 and not on its training weeks?
A model scores its own training data too well. A week that it never saw gives an honest count.
The idea
CI/CD means continuous integration (a build runs the same checks on every change) and continuous deployment or delivery (it releases only if they pass).
| Check | What it does | Finds |
|---|---|---|
| Code scanning (static analysis, SAST) | Reads code without running it and applies rules. SAST is static analysis for security faults. A linter is the same kind of tool, often for style. | A secret in code, SQL built from text |
| Software composition analysis (SCA) | Lists the components and matches each with known faults. The list is the SBOM (software bill of materials). | A dependency with a known fault |
| Unit test | One function, a fixed input. A regression test is kept after a fix, so the fault cannot return. | A function that does the wrong thing |
| Model test | The same for a model: fixed data and a floor on one measure. | A retrained model that got worse |
An AI review is not in the table. It can invent a fault, and it can miss one with no rule to explain why. So it gives leads, and these four checks are the gate: a program whose exit code stops the merge.
- Commit → Lint: rules on the code
- Lint → Composition scan: components against advisories
- Composition scan → Unit tests: unit and regression tests
- Unit tests → Model test: a floor on a measure
- Model test → Merge: all four exit with 0
- Model test → Build stops (blocked): a step ended with code 1
Any of the four steps can stop the build, not only the last one.
Worked example
1. Make the folders and save the program under review
cd (change directory) moves you into a folder. mkdir -p shop drafts makes two folders, shop and drafts, and makes parent folders too if they are missing. Both are new in this lesson.
cd ~/krlab/ai-for-secops
mkdir -p shop draftsshop/app.py has two planted faults. The first is a key written in the code. The second is an SQL text built from the order id: SQL injection means that text from a user becomes part of the SQL command, so the user changes the question. The id x' or '1'='1 makes the where test true for every row.
shop/app.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}The third fault is in a package, not in this file. The dependencies are in shop/requirements.txt, and the packages are invented.
shop/requirements.txt
krhttp==2.3.1
krpdf==1.2.0 # makes the PDF of a label
krtables==0.9.42. Scan the code with a rule checker
Save lint.py. The module ast (abstract syntax tree) reads a program as a tree of parts, so the checker sees structure and not letters. ast.walk visits every part, and isinstance asks its kind. SQL built with an f-string or a + is a JoinedStr or a BinOp passed to execute. This is security static analysis, like Bandit for Python, and not a style check. A real tool has hundreds of rules, and this one has four.
lint.py
"""lint.py: a small rule checker for the Python files of a folder. Exit code 1 for a security problem."""
import ast
import sys
from pathlib import Path
SECRET_WORDS = ("key", "secret", "token", "password")
def scan(path):
"""Return a list of (line, kind, message) for one file. kind is "security" or "quality"."""
tree = ast.parse(Path(path).read_text())
found, imported, used = [], {}, set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
imported.update({a.name: node.lineno for a in node.names})
elif isinstance(node, ast.Name):
used.add(node.id)
elif isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
for target in node.targets:
if isinstance(target, ast.Name) and any(w in target.id.lower() for w in SECRET_WORDS) and len(node.value.value) >= 8:
found.append((node.lineno, "security", f"a secret is written in the code: {target.id}"))
elif isinstance(node, ast.Call):
name = node.func.attr if isinstance(node.func, ast.Attribute) else getattr(node.func, "id", "")
if name == "execute" and node.args and isinstance(node.args[0], (ast.JoinedStr, ast.BinOp)):
found.append((node.lineno, "security", "an SQL text is built from pieces: use a parameter"))
if name in ("eval", "exec"):
found.append((node.lineno, "security", f"{name}() runs text as code"))
found += [(line, "quality", f"unused import: {name}") for name, line in imported.items() if name not in used]
return sorted(found)
if __name__ == "__main__":
problems = 0
for file in sorted(Path(sys.argv[1]).glob("*.py")):
for line, kind, message in scan(file):
print(f"{file}:{line}: [{kind}] {message}")
problems += kind == "security"
print("security problems:", problems)
sys.exit(1 if problems else 0)In lint.py, kind == "security" is True or False, and True counts as 1 when += adds it, so problems counts the security problems. getattr(node.func, "id", "") reads the attribute id and gives "" if there is none. echo "exit code $?" prints the exit code of the command before it.
python3 lint.py shop; echo "exit code $?"shop/app.py:2: [quality] unused import: os
shop/app.py:5: [security] a secret is written in the code: LABEL_KEY
shop/app.py:16: [security] an SQL text is built from pieces: use a parameter
security problems: 2
exit code 1A quality note does not stop the build. A security problem does.
3. Run a composition scan
Save advisories.json: invented advisories, each with a package and the version that fixed the fault. Real feeds give ranges, and you take them from the source. Then save sca.py. It writes the components to sbom.json and reports each one older than the fixed version. partition("==") cuts a text at the first ==.
advisories.json
[
{"id": "KR-ADV-0001", "package": "krpdf", "fixed": "1.2.5", "summary": "reads files outside its folder"},
{"id": "KR-ADV-0002", "package": "krhttp", "fixed": "2.2.0", "summary": "accepts a forged header"},
{"id": "KR-ADV-0003", "package": "krtables", "fixed": "0.9.0", "summary": "crashes on a long cell"}
]sca.py
"""sca.py: software composition analysis. Exit code 1 if a component is affected."""
import json
import sys
def version(text):
return tuple(int(part) for part in text.split(".")) # "1.2.0" becomes (1, 2, 0)
def components(path):
"""The name and version of each line of a requirements file. This list is a small SBOM."""
found = []
for line in open(path):
line = line.split("#")[0].strip()
if line:
name, _, number = line.partition("==")
found.append({"name": name, "version": number})
return found
def affected(parts, advisories):
"""The pairs (component, advisory) where the component is older than the fixed version."""
return [(c, a) for c in parts for a in advisories if a["package"] == c["name"] and version(c["version"]) < version(a["fixed"])]
if __name__ == "__main__":
parts = components(sys.argv[1])
open("sbom.json", "w").write(json.dumps(parts) + "\n")
hits = affected(parts, json.load(open(sys.argv[2])))
for c, a in hits:
print(f"{c['name']} {c['version']} is affected by {a['id']}: {a['summary']}. Fixed in {a['fixed']}.")
print("affected components:", len(hits))
sys.exit(1 if hits else 0)python3 sca.py shop/requirements.txt advisories.json; echo "exit code $?"krpdf 1.2.0 is affected by KR-ADV-0001: reads files outside its folder. Fixed in 1.2.5.
affected components: 1
exit code 1No line of app.py shows this fault. Only a comparison of versions with a list finds it. sbom.json is a plain list of names and versions. A real SBOM in CycloneDX or SPDX format adds more, such as package addresses and hashes.
4. Run the tests
Save test_app.py. sys.path is the list of folders where import looks, and sys.path.insert(0, "shop") puts shop first, so import app finds shop/app.py. failed += not ok adds 1 when a test did not pass. The second input, x' or '1'='1, becomes the regression test that keeps the injection from returning after a fix.
test_app.py
"""test_app.py: tests of the shop code. Exit code 1 if one fails."""
import sys
sys.path.insert(0, "shop")
import app
db, failed = app.connect(), 0
for name, ok in (("a known order is found", app.find_order(db, "A1") == [("A1", "alma", 12.5)]),
("a quote in the id is data, not SQL", app.find_order(db, "x' or '1'='1") == [])):
print(("ok " if ok else "FAIL ") + name)
failed += not ok
sys.exit(1 if failed else 0)python3 test_app.py; echo "exit code $?"ok a known order is found
FAIL a quote in the id is data, not SQL
exit code 15. Test the model against a floor
model_test.py is the same idea for the triage model of lesson 2. alerts(5) is the fixed week 5, train() trains the model on weeks 1 to 4, and scores gives each alert a score. The test counts the real incidents (label) that score 0.2 or more, and fails if there are fewer than 40 of the 59. The floor of 40 is a choice, like a threshold in lesson 2. sys.exit(found < 40) gives exit code 1 when that is true and 0 when it is false. This is the check that only an AI system needs: a model can get worse with no change in any line of code.
model_test.py
"""model_test.py: a test of the triage model. Fixed data, and a floor on one measure."""
import sys
from gen import alerts
from triage import scores, train
week = alerts(5)
found = sum(a["label"] and s >= 0.2 for a, s in zip(week, scores(train(), week)))
print(found, "of 59 incidents score 0.2 or more; the floor is 40")
sys.exit(found < 40)python3 model_test.py; echo "exit code $?"44 of 59 incidents score 0.2 or more; the floor is 40
exit code 0The model passes. A model retrained on bad data that finds 38 would end with exit code 1, and the build would stop before the release.
6. Put the checks in a pipeline
pipeline.py runs every step with subprocess.run (it runs a program; sys.executable is the Python that is running now) and ends with exit code 1 if any step failed. The AI review is not a step.
pipeline.py
"""pipeline.py: run the checks in order. Exit code 0 if every step passes, else 1."""
import subprocess
import sys
STEPS = [("lint", ["lint.py", "shop"]), ("composition scan", ["sca.py", "shop/requirements.txt", "advisories.json"]),
("unit tests", ["test_app.py"]), ("model test", ["model_test.py"])]
failed = []
for name, command in STEPS:
done = subprocess.run([sys.executable] + command, capture_output=True)
print(("pass " if done.returncode == 0 else "FAIL ") + name)
if done.returncode:
failed.append(name)
print("pipeline:", "failed in " + ", ".join(failed) if failed else "all steps passed")
sys.exit(1 if failed else 0)python3 pipeline.py; echo "exit code $?"FAIL lint
FAIL composition scan
FAIL unit tests
pass model test
pipeline: failed in lint, composition scan, unit tests
exit code 1Three steps fail, so the build does not merge. Each step found a different fault. The pipeline hides the output of a step (capture_output=True). To see why one failed, run that step alone, for example python3 lint.py shop.
Your turn
Fix the three faults of shop/app.py and shop/requirements.txt. Lesson 11 saves the faulty program again as its own file, so you may overwrite yours. Pass the order id to execute as a parameter: a ? in the SQL and a tuple as the second argument. Read the key from the environment with os.environ.get (the environment is the set of named values that the system gives to a program, so a key can stay out of the code). Move krpdf to the fixed version. Run pipeline.py until it ends with exit code 0. Then save a second draft, copy it into the shop with cp drafts/export.py shop/ (cp copies a file), and run python3 lint.py shop and the pipeline again.
drafts/export.py
"""export.py: the total of an order list, for the monthly report (a colleague's draft)."""
import csv
import json
def total_of(expression):
return eval(expression) # for example "12.5 + 80"Last, write two sentences on why a build with these checks is a better gate than a review. The page does not check this.
Check yourself
Why did no check of the code find the dependency fault?
The fault is in the package, not in your lines. Only components against advisories finds it, and the list changes weekly, so run the scan on a schedule too.
What does the regression test give you after the fix?
It keeps the fix: if someone writes an f-string query again, the build fails at once.
The model test passes with 44 and fails below 40. Who chooses 40, and when do you change it?
You choose it, from a rule about risk, as in lesson 2. Change it only on purpose and with a record of why, never to make a failing build pass.
A step prints "FAIL composition scan" and nothing else. What do you do?
Run that step alone, python3 sca.py shop/requirements.txt advisories.json, and read its lines. The pipeline hides them to keep the summary short.
Field notes
- Real tools: pip-audit (Python Packaging Authority) and OSV-Scanner (a front end to the OSV database) for composition scans, and Bandit for Python security checks. Read their current documentation first.
- SBOM formats: CycloneDX (ECMA-424) and SPDX. SPDX has an ISO text (ISO/IEC 5962:2021, which is version 2.2.1), and version 3 is newer. Take the current text from the source.
- Make the pipeline a required check, so nobody can merge around it.
- Run the composition scan on a schedule too, because a new advisory can make an old build unsafe.