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

Serve a model behind an API and test its good and bad requests

After this lesson you can
  • Load a trained model from a file that cannot run code
  • Validate every request and return one fixed answer shape
  • Prove the behaviour with a table of good and bad requests
Lab files of this lesson (11)

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 model of KR Books is trained and sits in a file. The team has a first plan for the service: "Load the pickle, take whatever JSON arrives, call predict." Your lead stops it: "A model file is code that somebody gave us, and the request body is text that a stranger wrote. Build the service so that neither can hurt it, and show me a table that proves it."

Recall

Lesson 1: in which zone is the service, and which part is the only one that may call it?

The service is inside. The gateway, which is at the edge, is the only part that may call it. A client that is outside must never reach it directly.

Lesson 1: what does an exit code of 1 from the checker tell a build?

At least one rule failed. A build treats exit code 0 as pass and any other code as fail, so a picture that breaks a rule cannot pass unnoticed.

The idea

A model service has five jobs. Each job answers one risk.

JobRisk it answers
Load the model from a safe file, and check its hashA model file that runs code, or one that was changed
Check the callerA request that did not come through the gateway
Check type, size and every fieldOversized bodies, wrong types, values the model never saw
Answer in one fixed shapeError text that leaks input, or output that the client cannot trust
Log without secretsA log that becomes the place where tokens and data leak

A pickle is Python's own format for saving objects, and scikit-learn models are usually saved this way (joblib files are pickles). Loading a pickle can run any code that the file's author chose. So the course saves a model as plain numbers in JSON: a weight for each feature, a bias, and the numbers for scaling. Loading JSON can only produce numbers and text.

What the service does with one request
Check callerCheck type and sizeParse and validateScoreFixed answertoken is righttype is JSON, body under 1024 byteswhole numbers in rangemodel, score, labelCheck callerCheck type and sizeParse and validateScoreFixed answer1234
  1. Check caller → Check type and size: token is right
  2. Check type and size → Parse and validate: type is JSON, body under 1024 bytes
  3. Parse and validate → Score: whole numbers in range
  4. Score → Fixed answer: model, score, label

The cheapest check that can refuse a request runs first, and a stranger learns nothing about the later checks.

Worked example

1. See why a pickle is not a safe file

pickle.dumps turns an object into bytes, and pickle.loads rebuilds it. __reduce__ tells pickle how to rebuild an object, and it may name any function to call. Here it is print, which is harmless.

cat > pickle_demo.py <<'EOT'
import pickle


class Trap:
    def __reduce__(self):
        return (print, ("this code ran while the file was loaded",))


data = pickle.dumps(Trap())
pickle.loads(data)
EOT
python pickle_demo.py
this code ran while the file was loaded

The data called print, not your program. Never load a pickle that you did not make.

2. Save the service

load_model reads the JSON, compares its hash with the manifest, and checks its shape. validate checks the fields. respond takes headers and a body and returns a status and an answer, with no network in it, so a test can call it. hmac.compare_digest compares two texts in a time that does not depend on where they differ. make_server wraps respond in a small web server (http.server) on 127.0.0.1.

service.py

"""service.py: a model service. It checks every request, answers in a fixed shape and logs no secrets.

    KR_GATEWAY_TOKEN=lab-token python3 service.py [port]       listens on 127.0.0.1 only
"""
import hashlib
import hmac
import json
import math
import os
import re
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

TOKEN = os.environ.get("KR_GATEWAY_TOKEN", "")
MAX_BODY = 1024
RANGES = {"failed": (0, 100), "new_device": (0, 1), "km": (0, 20000)}


def load_model(folder):
    """Load model.json from a folder, after its hash matches manifest.json. The file holds numbers only."""
    folder = Path(folder)
    text = (folder / "model.json").read_text()
    manifest = json.loads((folder / "manifest.json").read_text())
    if hashlib.sha256(text.encode()).hexdigest() != manifest["sha256"]:
        raise ValueError("model file does not match its manifest")
    model = json.loads(text)
    numbers = model["mean"] + model["scale"] + model["weights"] + [model["bias"]]
    if model["features"] != list(RANGES) or len(numbers) != 10 or any(type(v) not in (int, float) for v in numbers):
        raise ValueError("model file has the wrong shape")
    model["version"] = manifest["version"]
    return model


def score(model, x):
    """The probability that the event is suspicious: a weighted sum of scaled features, through a sigmoid."""
    z = model["bias"] + sum(w * (v - m) / s for v, m, s, w in zip(x, model["mean"], model["scale"], model["weights"]))
    return 1 / (1 + math.exp(-z))


def validate(data):
    """Return an error text, or None when the input is good. The text never repeats the input."""
    if not isinstance(data, dict):
        return "body must be a JSON object"
    if set(data) != set(RANGES):
        return "fields must be exactly: " + ", ".join(RANGES)
    for name, (low, high) in RANGES.items():
        if type(data[name]) is not int:
            return f"{name} must be a whole number"
        if not low <= data[name] <= high:
            return f"{name} must be from {low} to {high}"
    return None


def respond(model, headers, body):
    """One request in, (status, answer) out. No network here, so a test can call it."""
    h = {k.lower(): v for k, v in headers.items()}
    if not TOKEN or not hmac.compare_digest(h.get("x-gateway-token", "").encode(), TOKEN.encode()):
        return 401, {"error": "caller not allowed"}
    if h.get("content-type", "").split(";")[0].strip() != "application/json":
        return 415, {"error": "send application/json"}
    if len(body) > MAX_BODY:
        return 413, {"error": f"body over {MAX_BODY} bytes"}
    try:
        data = json.loads(body)
    except (ValueError, RecursionError):
        return 400, {"error": "body is not JSON"}
    problem = validate(data)
    if problem:
        return 400, {"error": problem}
    p = score(model, [data[f] for f in model["features"]])
    return 200, {"model": model["version"], "score": round(p, 2), "label": "suspicious" if p >= 0.5 else "normal"}


def make_server(model, port):
    class Handler(BaseHTTPRequestHandler):
        server_version, sys_version = "kr-service", ""
        timeout = 10   # a silent client cannot hold a thread for ever

        def do_POST(self):
            if self.path != "/predict":
                return self.send(404, {"error": "not found"})
            try:
                length = max(0, int(self.headers.get("Content-Length", "")))
            except ValueError:
                return self.send(400, {"error": "Content-Length needed"})
            body = self.rfile.read(min(length, MAX_BODY + 1))
            self.send(*respond(model, dict(self.headers), body))

        def do_GET(self):
            self.send(405, {"error": "use POST /predict"})

        def send(self, status, answer):
            client = self.headers.get("X-Client", "-")
            client = client if re.fullmatch(r"[a-z0-9_-]{1,32}", client) else "?"
            print(f"service {self.command} {self.path.split('?')[0][:40]} {status} client={client}", file=sys.stderr, flush=True)
            data = json.dumps(answer).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(data)))
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            self.wfile.write(data)

        def log_message(self, *args):
            pass

    return ThreadingHTTPServer(("127.0.0.1", port), Handler)


if __name__ == "__main__":
    if not TOKEN:
        sys.exit("set KR_GATEWAY_TOKEN first: the service refuses to start without it")
    server = make_server(load_model(os.environ.get("KR_MODEL_DIR", "models/current")), int(sys.argv[1]) if len(sys.argv) > 1 else 8421)
    print("service ready on 127.0.0.1", server.server_port, file=sys.stderr, flush=True)
    server.serve_forever()

Two choices are worth a second look. The service fails closed: with no KR_GATEWAY_TOKEN it refuses to start. The error texts name the rule and never repeat the input.

3. Prove the model file is checked

Copy the model, change one digit, and try to load it. sed -i edits a file in place. cp -r copies a folder with its contents.

cp -r models/v1 models/tampered
sed -i 's/5.317512/9.317512/' models/tampered/model.json
python -c "import service; service.load_model('models/tampered')"
rm -r models/tampered
ValueError: model file does not match its manifest

4. Write the table of requests

test_service.py holds a table: a name, the headers, the body, and the status that the service must return. unittest is the standard test library. A TestCase class holds tests, and subTest reports each table row on its own. The table uses two short forms of Python. {**GOOD, "X-Gateway-Token": "guess"} copies the dict GOOD and replaces one key. OK = lambda **fields: ... is a one-line function (a lambda) that collects its named arguments into the dict fields.

test_service.py

"""test_service.py: a table of good and bad requests, and what the service must answer.

    python3 test_service.py          prints the table, then runs the tests
"""
import contextlib
import io
import json
import os
import threading
import unittest
import urllib.error
import urllib.request

import service

service.TOKEN = "lab-token"
MODEL = service.load_model(os.path.join(os.path.dirname(os.path.abspath(__file__)), "models", "v1"))
GOOD = {"X-Gateway-Token": "lab-token", "Content-Type": "application/json"}
OK = lambda **fields: json.dumps({"failed": 0, "new_device": 0, "km": 5, **fields}).encode()

TABLE = [  # (name, headers, body, status that the service must return)
    ("quiet login", GOOD, OK(), 200),
    ("many failures, new device", GOOD, OK(failed=9, new_device=1, km=300), 200),
    ("no token", {"Content-Type": "application/json"}, OK(), 401),
    ("wrong token", {**GOOD, "X-Gateway-Token": "guess"}, OK(), 401),
    ("wrong content type", {**GOOD, "Content-Type": "text/plain"}, OK(), 415),
    ("body of 2000 bytes", GOOD, b" " * 2000, 413),
    ("not JSON", GOOD, b"failed=3", 400),
    ("JSON list", GOOD, b"[1, 2, 3]", 400),
    ("missing field", GOOD, b'{"failed": 1, "km": 5}', 400),
    ("extra field", GOOD, OK(admin=1), 400),
    ("text instead of number", GOOD, OK(failed="3"), 400),
    ("decimal number", GOOD, OK(failed=3.5), 400),
    ("true instead of number", GOOD, OK(new_device=True), 400),
    ("negative number", GOOD, OK(failed=-1), 400),
    ("number out of range", GOOD, OK(km=20001), 400),
    ("deeply nested JSON", GOOD, b"[" * 900, 400),
]


class ServiceTests(unittest.TestCase):
    def test_table(self):
        for name, headers, body, want in TABLE:
            with self.subTest(name):
                self.assertEqual(service.respond(MODEL, headers, body)[0], want)

    def test_answer_has_a_fixed_shape(self):
        status, answer = service.respond(MODEL, GOOD, OK())
        self.assertEqual(sorted(answer), ["label", "model", "score"])
        self.assertEqual(service.respond(MODEL, GOOD, b"x")[1], {"error": "body is not JSON"})

    def test_log_holds_no_secret(self):
        server = service.make_server(MODEL, 8431)
        threading.Thread(target=server.serve_forever, daemon=True).start()
        log = io.StringIO()
        with contextlib.redirect_stderr(log):
            request = urllib.request.Request("http://127.0.0.1:8431/predict", OK(), {**GOOD, "X-Client": "alpha fake line"})
            urllib.request.urlopen(request).read()
        server.shutdown()
        server.server_close()
        self.assertEqual(log.getvalue().count("\n"), 1)
        self.assertNotIn("lab-token", log.getvalue())
        self.assertNotIn("failed", log.getvalue())


if __name__ == "__main__":
    for name, headers, body, want in TABLE:
        print(f"{service.respond(MODEL, headers, body)[0]}  {name}")
    unittest.main(argv=["test_service"])
python test_service.py
200  quiet login
200  many failures, new device
401  no token
401  wrong token
415  wrong content type
413  body of 2000 bytes
400  not JSON
400  JSON list
400  missing field
400  extra field
400  text instead of number
400  decimal number
400  true instead of number
400  negative number
400  number out of range
400  deeply nested JSON
...
----------------------------------------------------------------------
Ran 3 tests in 0.527s

OK

The last test starts the real server on port 8431, sends a client name with a space (it fails the pattern), and checks that the log has one line, no token and no field names.

5. Start the service and call it

Put the model in the folder that the service reads. Then start it in the background with &. $! is the process number of the last background job. lab-token is a lab value: lesson 4 makes real ones.

mkdir -p models/current
cp models/v1/model.json models/v1/manifest.json models/current/
KR_GATEWAY_TOKEN=lab-token python service.py 8421 2> service.log &
echo $! > service.pid
sleep 1

curl sends a web request. -s hides the progress bar, -X POST sets the method, -H adds a header, -d sets the body, and -w prints extra text after the answer (here the status code).

curl -s -w ' %{http_code}\n' -X POST -H 'X-Gateway-Token: lab-token' -H 'Content-Type: application/json' -d '{"failed": 5, "new_device": 1, "km": 100}' http://127.0.0.1:8421/predict
curl -s -w ' %{http_code}\n' -X POST -H 'X-Gateway-Token: lab-token' -H 'Content-Type: application/json' -d '{"failed": 5, "km": 100}' http://127.0.0.1:8421/predict
curl -s -w ' %{http_code}\n' -X POST -d '{"failed": 5}' http://127.0.0.1:8421/predict
{"model": "v1", "score": 0.8, "label": "suspicious"} 200
{"error": "fields must be exactly: failed, new_device, km"} 400
{"error": "caller not allowed"} 401

6. Read the log, then stop the service

A log line has five parts. The query string is the part of a URL after ?, for example /predict?key=abc. It can hold a key, so the log never keeps it.

A log line of the service
servicethe programPOSTthe method/predictthe path, no query string200the statusclient=-the client name, or - when noneservicethe programPOSTthe method/predictthe path, no query string200the statusclient=-the client name, or - when none
cat service.log
kill $(cat service.pid)
service ready on 127.0.0.1 8421
service POST /predict 200 client=-
service POST /predict 400 client=-
service POST /predict 401 client=-

Three requests, three lines.

Your turn

A colleague recorded eight requests in requests-02.json. Save it in your lab folder. Each entry has a name, headers and a body (text).

requests-02.json

[
  {"name": "login 1", "headers": {"X-Gateway-Token": "lab-token", "Content-Type": "application/json"}, "body": "{\"failed\": 5, \"new_device\": 0, \"km\": 200}"},
  {"name": "login 2", "headers": {"X-Gateway-Token": "lab-token", "Content-Type": "application/json"}, "body": "{\"failed\": 4, \"new_device\": 1, \"km\": 120}"},
  {"name": "login 3", "headers": {"X-Gateway-Token": "lab-token", "Content-Type": "application/json"}, "body": "{\"failed\": 5, \"new_device\": 1, \"km\": 100}"},
  {"name": "login 4", "headers": {"X-Gateway-Token": "lab-token", "Content-Type": "application/json"}, "body": "{\"failed\": 101, \"new_device\": 0, \"km\": 10}"},
  {"name": "login 5", "headers": {"X-Gateway-Token": "lab-token", "Content-Type": "application/json"}, "body": "{\"failed\": 3, \"new_device\": 2, \"km\": 10}"},
  {"name": "login 6", "headers": {"X-Gateway-Token": "lab-token", "Content-Type": "application/json"}, "body": "failed=3&km=10"},
  {"name": "login 7", "headers": {"Content-Type": "application/json"}, "body": "{\"failed\": 1, \"new_device\": 0, \"km\": 10}"},
  {"name": "login 8", "headers": {"X-Gateway-Token": "lab-token", "Content-Type": "text/plain"}, "body": "{\"failed\": 1, \"new_device\": 0, \"km\": 10}"}
]

Write table02.py. It loads the model from models/v1, sets service.TOKEN to lab-token, runs every request through service.respond (encode the body to bytes first), and prints one line for each request with its name, the status and the answer. Then answer from your own output.

Check yourself

Why does the service reject a body with an extra field, such as "admin": 1, and not ignore it?

A field that the service does not know should never arrive. If it does, the client has a bug or someone is probing, and ignoring it hides both. A strict shape also stops the day when later code starts to read that field and trusts it.

The JSON model file is not signed. What stops someone from changing both the model and the manifest?

Nothing in this lesson. The hash catches accidents and a changed model file, not an attacker who can write both files. Lesson 5 makes the files read-only and lesson 6 records the hash in a registry that only the release script writes. A signature would close the gap, and lesson 6 names it.

Why does the answer give a score rounded to two decimals, and not the raw number?

A raw probability with many digits gives an attacker more information to rebuild the model by asking many questions. Two decimals are enough for the client's decision. Lesson 7 of "Securing models and the ML supply chain" shows how many answers rebuild a model.

Field notes

  • Prefer a format that holds only data for model files: JSON of numbers here, and formats such as safetensors or ONNX for larger models. If you must load a pickle, load it only in a sandbox, and only from a source that you verified (lesson 5).
  • A real service runs in a container image with a fixed Python, and the platform restarts it when it fails. The course cannot test a container, but the checks of this lesson are the same inside one.
  • Set a body limit twice: in the gateway (lesson 3) and in the service. The service must stay safe if somebody reaches it another way.
  • Never put the model's raw error messages in the reply. Log a request id and return the id, so that support can find the details.