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 10 · 45 minutes

Build a production readiness check for the whole lab system

After this lesson you can
  • Turn a launch checklist into one script that prints PASS or FAIL for each item
  • Check the architecture, gateway, keys, files, isolation, release, drift, budgets and policy from their evidence
  • Break the system on purpose and read what the check reports
Lab files of this lesson (41)

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 launch meeting is on Friday. In earlier launches the question "are we ready?" got the answer "I think so", and twice that was wrong. Your lead asks for a different kind of answer: "A page with ten lines, each PASS or FAIL, produced by a script that reads the real files. If any line says FAIL, we do not launch." You build that script from the programs of the whole course. It does not prove that the system is safe. It proves that ten things that you decided to require are in place, and it says so every time.

Recall

Lesson 9: what does the policy evaluator return for a request that no rule mentions?

Deny, with the reason "no rule allows this". A missing rule is never an opening.

Lesson 6: what does the registry record for a promoted version, and who may write it?

The hash of the model file, the scores, the names of the gates that passed, and the date. Only the release script writes it.

The idea

A readiness check is a list of requirements, and for each one a piece of evidence that a program can read. A good item has three parts: what is required, where the evidence is, and what counts as a pass. Two habits make the check honest. First, the check fails closed: a file that is missing or broken is a FAIL, never a pass. Second, it reads the system as it is now (files, hashes, test results), and not a statement that someone wrote about it.

ItemEvidencePasses when
architecturearchitecture.jsonThe six rules of lesson 1 hold
gateway limitsgateway.jsonrate, window and max_body are set
gateway testsThe tests of lessons 2 and 3, in the lab folderThey pass
key agekeys.jsonHashes only, and no key lives longer than 90 days
file modesThe whole folderNo stray keys, secret files private, model not writable by others
isolationsettings.jsonThe seven rules of lesson 5 hold for the written settings
release gatesmodels/registry.jsonThe current model passed every gate and its file is unchanged
drift reportdrift/report.jsonIt is at most 7 days old and not alert
budgetsbudget.jsonEvery client of keys.json has a budget
policy testspolicy-cases.jsonEvery case gets the expected decision

The script takes a folder (--root) and a date (--today), so that you can check another system, or the same system on another day, and so that a test gives the same answer on every machine. In this lab, "today" is 2026-11-21 in every run.

What the readiness check reads
Lab folderCheckArchitectureGateway filesKeysModel registryVerdictReadiness script12345Lab folderCheckArchitectureGatewayfilesKeysModelregistryVerdictReadiness script12345
  1. Readiness script → Architecture: do the six rules hold?
  2. Readiness script → Gateway files: are the limits set?
  3. Readiness script → Keys: hashes only, none over 90 days?
  4. Readiness script → Model registry: did the model pass every gate?
  5. Readiness script → Verdict: PASS or FAIL for each item

Worked example

1. Clean up, write the settings and make the drift report

The check reads the whole lab folder, so leftovers from earlier lessons count. Remove the demo files, if they exist (rm -rf removes without a question: read the names first). The isolation item audits the settings of the service as written down in settings.json, the values that lesson 5 gave it. Lesson 5 audited the running process, and this file is only the plan, so audit the process too. Then make the drift report that the check expects, dated with the fixed day (lesson 7).

settings.json

{"uid": 1000, "model_mode": "444", "work_mode": "700", "secret_modes": ["600", "600", "600"],
 "nofile": 64, "memory": 2147483648, "fsize": 10485760}
rm -rf scan-demo demo-secrets demo-keys.json models/v6 models/tampered
mkdir -p drift
cp samples/reference.json drift/reference.json
cp samples/live-a.json drift/live.json
python drift.py drift/reference.json drift/live.json --out drift/report.json --today 2026-11-21 | tail -1
overall: ok

2. Save the check

Each item is a function that returns (passed, detail). main runs them all and turns a missing or broken file (OSError, KeyError, ValueError) into a FAIL line. The items reuse the programs of the course: arch_check.check (lesson 1), scan_secrets.scan (lesson 4), audit_isolation.audit (lesson 5), release.load_registry and release.GATES (lesson 6), and policy.failed_cases (lesson 9). run_tests starts the unit tests in a separate process, as the release script does.

readiness.py

"""readiness.py: check a system against the launch checklist. One line for each item: PASS or FAIL.

    python3 readiness.py [--root DIR] [--today 2026-11-30]        exit code 0 only when every item passes
DIR holds architecture.json, gateway.json, keys.json, secrets/, settings.json, models/, budget.json, policy.json, policy-cases.json and drift/.
"""
import hashlib
import json
import re
import stat
import subprocess
import sys
from datetime import date
from pathlib import Path

import arch_check
import audit_isolation
import policy
import release
import scan_secrets

HERE = Path(__file__).resolve().parent
MAX_KEY_AGE = 90
DRIFT_MAX_AGE = 7


def load(root, name):
    return json.loads(Path(root, name).read_text())


def run_tests(*modules):
    return subprocess.run([sys.executable, "-m", "unittest", "-q", *modules], cwd=HERE, capture_output=True).returncode == 0


def item_architecture(root, today):
    failed = [rule for rule, ok, _ in arch_check.check(load(root, "architecture.json")) if not ok]
    return not failed, "all rules hold" if not failed else "fails: " + ", ".join(failed)


def item_limits(root, today):
    config = load(root, "gateway.json")
    missing = [k for k in ("rate", "window", "max_body") if not isinstance(config.get(k), int) or config[k] <= 0]
    return not missing, "rate, window and max_body are set" if not missing else "not set: " + ", ".join(missing)


def item_gateway_tests(root, today):
    ok = run_tests("test_gateway", "test_service")
    return ok, "gateway and service tests pass" if ok else "gateway or service tests fail"


def item_keys(root, today):
    keys = load(root, "keys.json")["keys"]
    days = lambda a, b: (date.fromisoformat(a) - date.fromisoformat(b)).days
    long_lived = [k["id"] for k in keys if days(k["expires"], k["created"]) > MAX_KEY_AGE or (k["expires"] > today and days(today, k["created"]) > MAX_KEY_AGE)]
    not_hashed = [k["id"] for k in keys if not re.fullmatch(r"[0-9a-f]{64}", k["hash"])]
    problems = [f"older than {MAX_KEY_AGE} days: {long_lived}"] * bool(long_lived) + [f"not hashed: {not_hashed}"] * bool(not_hashed)
    return not problems, f"{len(keys)} keys, none older than {MAX_KEY_AGE} days" if not problems else "; ".join(problems)


def item_file_modes(root, today):
    found = scan_secrets.scan(root)
    model = stat.S_IMODE(Path(root, "models", "current", "model.json").stat().st_mode)
    problems = [f"{where} {what}" for where, what in found] + (["model file is writable by others"] if model & 0o022 else [])
    return not problems, "no stray keys, secret files private" if not problems else "; ".join(problems)


def item_isolation(root, today):
    failed = [name for name, ok, _ in audit_isolation.audit(audit_isolation.read_settings(Path(root, "settings.json"))) if not ok]
    return not failed, "the seven rules hold" if not failed else "fails: " + ", ".join(failed)


def item_release(root, today):
    registry = release.load_registry(root)
    entry = registry["versions"].get(registry["current"]) or {}
    text = Path(root, "models", "current", "model.json").read_text()
    ok = entry.get("gates") == release.GATES and entry.get("sha256") == hashlib.sha256(text.encode()).hexdigest()
    return ok, f"{registry['current']} passed every gate and the file is unchanged" if ok else f"{registry['current']} has no proof of the gates, or its file changed"


def item_drift(root, today):
    path = Path(root, "drift", "report.json")
    if not path.exists():
        return False, "no drift report"
    report = json.loads(path.read_text())
    age = (date.fromisoformat(today) - date.fromisoformat(report["date"])).days
    return age <= DRIFT_MAX_AGE and report["status"] != "alert", f"status {report['status']}, {age} days old"


def item_budgets(root, today):
    clients = {k["client"] for k in load(root, "keys.json")["keys"]}
    missing = sorted(clients - set(load(root, "budget.json")))
    return not missing, "every client has a budget" if not missing else "no budget for: " + ", ".join(missing)


def item_policy(root, today):
    cases = load(root, "policy-cases.json")
    wrong = policy.failed_cases(load(root, "policy.json")["rules"], cases)
    return bool(cases) and not wrong, f"{len(cases)} cases decided as expected" if cases and not wrong else f"{len(wrong)} wrong of {len(cases)} cases"


ITEMS = [("architecture", item_architecture), ("gateway limits", item_limits), ("gateway tests", item_gateway_tests),
         ("key age", item_keys), ("file modes", item_file_modes), ("isolation", item_isolation), ("release gates", item_release),
         ("drift report", item_drift), ("budgets", item_budgets), ("policy tests", item_policy)]


def main(argv):
    root = argv[argv.index("--root") + 1] if "--root" in argv else "."
    today = argv[argv.index("--today") + 1] if "--today" in argv else date.today().isoformat()
    passed = 0
    for name, item in ITEMS:
        try:
            ok, detail = item(root, today)
        except (OSError, KeyError, ValueError) as error:   # a missing or broken file is a failure, not a crash
            ok, detail = False, f"cannot check: {type(error).__name__} {error}"
        passed += ok
        print(("PASS  " if ok else "FAIL  ") + name.ljust(15) + detail)
    print(f"readiness: {passed} of {len(ITEMS)} pass")
    return 0 if passed == len(ITEMS) else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

3. Run it

python readiness.py --today 2026-11-21
echo "exit code $?"
PASS  architecture   all rules hold
PASS  gateway limits rate, window and max_body are set
PASS  gateway tests  gateway and service tests pass
PASS  key age        2 keys, none older than 90 days
PASS  file modes     no stray keys, secret files private
PASS  isolation      the seven rules hold
PASS  release gates  v1 passed every gate and the file is unchanged
PASS  drift report   status ok, 0 days old
PASS  budgets        every client has a budget
PASS  policy tests   8 cases decided as expected
readiness: 10 of 10 pass
exit code 0

The item gateway tests runs the tests that sit next to readiness.py, whatever --root says: it tests the lab's code, not the code in the folder under review. Read the detail of each line. They are the evidence: "v1 passed every gate and the file is unchanged" means that the registry and the file agree. It does not prove that the gates ran, because the registry holds only their names. If a line says FAIL, read its detail: the check tells you which file or which key.

4. Break two things on purpose

First give a key file a mode that other users can read. Then look at the system on a day in the future, when the drift report is old.

chmod 644 secrets/alpha.key
python readiness.py --today 2026-11-21 | grep -E 'FAIL|readiness'
chmod 600 secrets/alpha.key
python readiness.py --today 2027-03-01 | grep -E 'FAIL|readiness'
FAIL  file modes     secrets/alpha.key secret file with mode 644
readiness: 9 of 10 pass
FAIL  drift report   status ok, 100 days old
readiness: 9 of 10 pass

The first run names the file and its mode. The second run fails on the age of the drift report only: on that date the keys have expired, so the key rule has nothing active to complain about. Whoever does the lab on whatever day gets the same lines. A check that runs every day finds this kind of drift by itself: nothing was changed, and yet the system is no longer ready.

5. The finished files

The check uses files of earlier lessons, all printed whole there and unchanged since. This table is the finished lab, with the lesson that made each part.

The finished lab, file by file
FilesLessonJob
data.py, train.py, labcheck.py0Fixed data, a model as plain JSON, the lab check
architecture.json, arch_check.py1The picture as a file, and its checker
service.py, test_service.py2The model service and its table of requests
gateway.py, keystore.py, gateway.json, test_gateway.py3The front door, keys as hashes, limits and tests
rotate.py, scan_secrets.py, test_keys.py4Rotation with overlap, the secret scanner
audit_isolation.py, settings.json5, 10The audit of the isolation settings, and the written settings
release.py, models/registry.json6Six gates, promotion, rollback
drift.py, drift/report.json7Two measures, alert rules, the report
budget.py, capacity.py, budget.json8Budgets, load shedding, capacity
policy.py, policy.json, policy-cases.json9Rules as data and their test table
readiness.py10One check for all of it

Your turn

Use the check on your own lab, with --today 2026-11-21 unless a task names another date. Run it, then do these four things one at a time, and restore the system after each one: give secrets/alpha.key mode 644, run the check for the date 2027-03-01, rename drift/report.json and run the check, and add a line api_key = kr_abcdefghijklmnopqrstuvwxyz to a new file notes.txt in the lab folder (remove it afterwards). Then write an item of your own (for example, "the audit log holds no key") and a case that makes it fail.

Check yourself

The check says 10 of 10. Does that mean the system is secure?

No. It means that ten requirements you chose are met. It cannot see a bug in the model code, a stolen key that is still valid, a weak rule in the policy, or a risk that is not on the list. A readiness check removes the cheap mistakes, and the review of risks is still needed (the threat modelling lessons of AI security fundamentals say how).

Why does a missing drift report give FAIL and not "not applicable"?

An item that can pass by being absent turns into a way to skip the control. "No drift check" is exactly the state that the item exists to catch. If a requirement does not apply to a system, remove it from the list, in a change that someone reviews.

Why does the check run the unit tests again if the release script ran them?

The release ran them for one version at one time. The code of the gateway and the service can change after that. The check proves the state of today, so it reads the files and runs the tests now.

Field notes

  • Run the check in CI on every change, and also on a timer (daily) against the running system. Drift, expired keys and old reports show up with no change at all.
  • Keep every item small, fast and independent. When one breaks, the others still report. Print the evidence in the detail, so that nobody has to guess.
  • Version the checklist. A requirement that is dropped, or a threshold that is relaxed, is a security decision. It needs a name and a reason in the history.
  • A pass is not a certificate. KaliRange does not certify systems, and a real launch may also need a review of the law, the data protection, the supplier and the people who run it.
  • Make the failure output usable at 03:00: one line, the item, the file, the next step.