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 01 · 35 minutes

Draw the reference architecture of a model service and check it

After this lesson you can
  • Name the parts of a model service and the zone of each one
  • Describe every connection by what crosses it and the control on it
  • Check an architecture file with a program and fix the gaps that it finds
Lab files of this lesson (7)

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 team at KR Books wants to launch "login-risk", a model that scores a login attempt as normal or suspicious. Your lead asks for a one-page picture before anyone writes a line of deployment code: "Show me every part, who owns it, and what protects each connection. If a connection has no protection, I want to see that on the page." You draw the picture as a file that a program can check, so that the picture cannot drift away from the truth.

The idea

A model in production is a small system, not a file. A client sends a request. A gateway (the one front door) checks it. A service loads a model and answers. Around them sit a model store (the versions of the model), a data store (training and reference data), a pipeline (the programs that build and release models), logs, and secrets (keys and tokens).

A trust boundary is a line between two parts that do not trust each other equally. You put each part in a zone:

ZonePartsRule
outsidethe clientNot trusted. It may reach only the edge.
edgethe gatewayThe one door. It faces the outside and the inside.
insideservice, stores, pipeline, logs, secretsReached only from the edge or from other inside parts.

A connection goes from one part to another. For each one you write what crosses it (the data) and the control on it (what stops misuse). A connection that crosses a boundary and has no control is the most common gap in a launch review.

One request and the boundaries it crosses
OutsideEdgeInsideAttackerClientGatewayModel serviceModel storeSecrets12345OutsideEdgeInsideAttackerClientGatewayModel serviceModel storeSecrets12345
  1. Client → Gateway: request and API key
  2. Gateway → Secrets: key hashes and gateway token
  3. Gateway → Model service: request and gateway token
  4. Model service → Model store: read model.json
  5. Attacker → Model service (blocked): direct call

A real platform has an equivalent for each part: a load balancer or managed API gateway, a container for the service, an object store for models, a secrets manager. This course cannot test those, so every lesson builds the part on your laptop and names the equivalent.

Worked example

1. Write the table as a file

The file architecture.json holds the table. JSON is a text format for lists and for pairs of name and value. Each part has an owner (the team that answers for it) and a zone. A part that listens on a port has a listen address. 127.0.0.1 is your own computer only. Each connection has four fields:

One connection of architecture.json
clientfrom: the part that sendsgatewayto: the part that receivesAPI key, request JSONcarries: the dataAPI key, rate limit, size limitcontrolclientfrom: the part that sendsgatewayto: the part that receivesAPI key, request JSONcarries: the dataAPI key, rate limit, size limitcontrol

architecture.json

{
 "components": {
  "client": {"owner": "app team", "zone": "outside"},
  "gateway": {"owner": "platform team", "zone": "edge", "listen": "127.0.0.1:8420"},
  "service": {"owner": "ml team", "zone": "inside", "listen": "127.0.0.1:8421"},
  "model-store": {"owner": "ml team", "zone": "inside"},
  "data-store": {"owner": "data team", "zone": "inside"},
  "pipeline": {"owner": "ml team", "zone": "inside"},
  "logs": {"owner": "security team", "zone": "inside"},
  "secrets": {"owner": "security team", "zone": "inside"}
 },
 "connections": [
  {"from": "client", "to": "gateway", "carries": "API key, request JSON", "control": "API key, rate limit, size limit"},
  {"from": "gateway", "to": "service", "carries": "request JSON, gateway token", "control": "shared token, loopback only"},
  {"from": "service", "to": "model-store", "carries": "model.json", "control": "read-only file, hash check"},
  {"from": "pipeline", "to": "model-store", "carries": "new model version", "control": "release gates"},
  {"from": "pipeline", "to": "data-store", "carries": "training samples", "control": "read-only account"},
  {"from": "gateway", "to": "logs", "carries": "audit lines", "control": "no keys, no bodies"},
  {"from": "service", "to": "logs", "carries": "log lines", "control": "no keys, no bodies"},
  {"from": "gateway", "to": "secrets", "carries": "key hashes, gateway token", "control": "files of mode 600"},
  {"from": "service", "to": "secrets", "carries": "gateway token", "control": "files of mode 600"}
 ]
}

2. Write the checker

arch_check.py turns six rules into code. A list comprehension, such as [n for n, p in parts.items() if ...], builds a list from the items that pass a test. A lambda is a function in one line: lambda x: x + 1 takes x and gives back x + 1. sys.exit(1) ends the program with exit code 1, which means "failed". A program that other programs can judge by its exit code is a program that a pipeline can use.

arch_check.py

"""arch_check.py: check an architecture file. Every part has an owner and a zone, every connection has a control.

    python3 arch_check.py architecture.json [--table]        exit code 1 when a rule fails
"""
import json
import sys

ZONES = ("outside", "edge", "inside")


def check(arch):
    """Return (rule, ok, detail) for each rule. A boundary is crossed when two parts are in different zones."""
    parts, links = arch["components"], arch["connections"]
    names = lambda bad: ", ".join(bad) or "none"
    no_owner = [n for n, p in parts.items() if not p.get("owner")]
    bad_zone = [n for n, p in parts.items() if p.get("zone") not in ZONES]
    unknown = [f"{c['from']}->{c['to']}" for c in links if c["from"] not in parts or c["to"] not in parts]
    no_control = [f"{c['from']}->{c['to']}" for c in links if c.get("control", "none").strip().lower() in ("", "none")]
    zone = lambda n: parts.get(n, {}).get("zone")
    skipped = [f"{c['from']}->{c['to']}" for c in links if zone(c["from"]) == "outside" and zone(c["to"]) == "inside"]
    open_port = [n for n, p in parts.items() if p.get("zone") == "inside" and p.get("listen") and not p["listen"].startswith("127.")]
    return [("every part has an owner", not no_owner, "missing: " + names(no_owner)),
            ("every part has a zone", not bad_zone, "missing: " + names(bad_zone)),
            ("every connection joins known parts", not unknown, "unknown: " + names(unknown)),
            ("every connection has a control", not no_control, "no control: " + names(no_control)),
            ("nothing outside reaches inside", not skipped, "direct: " + names(skipped)),
            ("inside parts listen on loopback", not open_port, "open: " + names(open_port))]


if __name__ == "__main__":
    with open(sys.argv[1]) as f:
        arch = json.load(f)
    if "--table" in sys.argv:
        for c in arch["connections"]:
            zone = lambda n: arch["components"].get(n, {}).get("zone")
            crosses = zone(c["from"]) != zone(c["to"])
            print(f"{c['from']:9} -> {c['to']:12} {'crosses' if crosses else 'inside ':7} {c['carries']} | {c['control']}")
    results = check(arch)
    for rule, ok, detail in results:
        print(("ok   " if ok else "FAIL ") + rule.ljust(36) + ("" if ok else detail))
    print(f"architecture ok: {sum(ok for _, ok, _ in results)} of {len(results)}")
    sys.exit(0 if all(ok for _, ok, _ in results) else 1)

3. Run it and read the table

--table prints one line for each connection and says whether it crosses a zone boundary.

python arch_check.py architecture.json --table
client    -> gateway      crosses API key, request JSON | API key, rate limit, size limit
gateway   -> service      crosses request JSON, gateway token | shared token, loopback only
service   -> model-store  inside  model.json | read-only file, hash check
pipeline  -> model-store  inside  new model version | release gates
pipeline  -> data-store   inside  training samples | read-only account
gateway   -> logs         crosses audit lines | no keys, no bodies
service   -> logs         inside  log lines | no keys, no bodies
gateway   -> secrets      crosses key hashes, gateway token | files of mode 600
service   -> secrets      inside  gateway token | files of mode 600
ok   every part has an owner
ok   every part has a zone
ok   every connection joins known parts
ok   every connection has a control
ok   nothing outside reaches inside
ok   inside parts listen on loopback
architecture ok: 6 of 6

Four connections cross a boundary. Each one has a control that you can test later in the course: lesson 3 tests the first two, lesson 4 the key files, and lessons 2 and 3 the log lines. Lesson 5 tests the read-only model, an inside connection.

4. Break it on purpose

sed 's/old/new/' replaces the first old on each line with new. Make a copy of the file in which the release pipeline has no control, then run the checker on it. $? holds the exit code of the last command.

sed 's/"release gates"/"none"/' architecture.json > broken.json
python arch_check.py broken.json
echo "exit code $?"
ok   every part has an owner
ok   every part has a zone
ok   every connection joins known parts
FAIL every connection has a control      no control: pipeline->model-store
ok   nothing outside reaches inside
ok   inside parts listen on loopback
architecture ok: 5 of 6
exit code 1

A checker that says FAIL and exits with 1 is the base of the whole course: lesson 6 uses the same idea to block a release, and lesson 10 to block a launch.

Your turn

A colleague drew a first version of the same system and saved it as architecture-draft.json. Save it in your lab folder.

architecture-draft.json

{
 "components": {
  "client": {"owner": "app team", "zone": "outside"},
  "gateway": {"owner": "platform team", "zone": "edge", "listen": "127.0.0.1:8420"},
  "service": {"owner": "ml team", "zone": "inside", "listen": "0.0.0.0:8421"},
  "model-store": {"owner": "ml team", "zone": "inside"},
  "data-store": {"owner": "data team", "zone": "inside"},
  "pipeline": {"owner": "ml team", "zone": "inside"},
  "logs": {"owner": "", "zone": "inside"},
  "secrets": {"owner": "security team", "zone": "inside"}
 },
 "connections": [
  {"from": "client", "to": "gateway", "carries": "API key, request JSON", "control": "API key, rate limit, size limit"},
  {"from": "client", "to": "service", "carries": "request JSON", "control": "API key"},
  {"from": "gateway", "to": "service", "carries": "request JSON, gateway token", "control": "shared token, loopback only"},
  {"from": "service", "to": "model-store", "carries": "model.json", "control": "read-only file, hash check"},
  {"from": "pipeline", "to": "model-store", "carries": "new model version", "control": "release gates"},
  {"from": "pipeline", "to": "data-store", "carries": "training samples", "control": "none"},
  {"from": "gateway", "to": "logs", "carries": "audit lines", "control": "no keys, no bodies"},
  {"from": "service", "to": "logs", "carries": "log lines", "control": "no keys, no bodies"},
  {"from": "gateway", "to": "secrets", "carries": "key hashes, gateway token", "control": "files of mode 600"},
  {"from": "service", "to": "secrets", "carries": "gateway token", "control": "files of mode 600"}
 ]
}

Run the checker on the draft. Then copy it to architecture-fixed.json and correct the copy until the checker prints architecture ok: 6 of 6. Do not delete the gateway or any control: fix the cause of each failure. Decide yourself who owns the logs (a team that already appears in the file) and which control the training data needs.

Check yourself

Why does a model store sit inside, and not at the edge?

Nobody outside needs to reach it. Every part that can be reached from outside is a part that attackers can try. The model store holds the files that decide every answer of the service, so only the service (read) and the pipeline (write) get a connection to it.

The checker passes, but a gateway does not exist in the running system. What did the checker prove?

Only that the file is consistent. A drawing is a claim about the system, not proof of it. That is why the later lessons add tests that touch the real programs, and why lesson 10 checks the running files and not only the picture.

Why must a service that listens only on 127.0.0.1 still check a token from the gateway?

Any program on the same computer can connect to 127.0.0.1, including a program that an attacker started. The loopback address limits who can reach the port from the network. The token limits who may use it on the computer itself. Lesson 3 builds both.

Field notes

  • A diagram with trust boundaries is the input of a threat model. For each connection that crosses a boundary, ask the six STRIDE questions: spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege.
  • Keep the file in version control next to the code, and run the checker in the build. A picture on a wiki page is out of date within weeks.
  • Give every part one named owner, a team and not a person. At 03:00 the owner is who you wake up.
  • Add the control as a test, not as a sentence: "rate limit" is only true once a test sends 20 requests and sees 15 of them refused (lesson 3).
  • The OWASP Top 10 for LLM Applications and the NIST AI Risk Management Framework both expect that you know your parts and your data flows. This file is the smallest useful form of that record.