Lesson 03 · 45 minutes
Put a gateway in front of the model service and test each control
- Build a gateway that checks an API key, a rate limit and a body size before it forwards
- Make the service accept calls from the gateway only
- Prove each control with a status code that code decides
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 service from lesson 2 checks its input, but any program on the computer can still call it, as often as it likes. Three teams will use the model. Your lead wants one front door: "Each team gets its own key. No team may use up the capacity of the others. Every call leaves a log line. Each promise gets a test."
Recall
Lesson 2: why does the service check the token before it looks at the body?
The cheapest check runs first.
Lesson 1: which connections of the architecture file does this lesson turn into tested controls?
client -> gateway and gateway -> service. Until a test reads a status code, a control is only a claim.
The idea
A gateway is one program in front of the model service. Every request passes through it, and it decides before the model sees anything.
| Control | A request that breaks it gets |
|---|---|
| Authenticate: the API key is known and not expired | 401 |
Authorise: the key has the scope predict | 403 |
| Size limit: the body is small enough | 413 |
| Rate limit: at most N requests per window for this key | 429 and Retry-After |
| Audit: one line for every request | (the log) |
| Forward: pass it on with the gateway token | what the service returns |
The gateway is a list of small functions called stages. A stage says nothing (the request goes on) or returns a status and a reason (the request stops). decide runs them in order with no network work, so a test can call it with a made-up request.
- Client → Gateway: POST /predict with a key
- Gateway: check key, scope, size and rate
- Gateway → Client: a check fails: 401, 403, 413 or 429
- Gateway → Service: all pass: request and gateway token
- Service → Gateway: score and label
- Gateway → Client: the answer, after one audit line
Worked example
1. Save the key store
A hash is a fingerprint of a text. It cannot be turned back into the text, and a long random key cannot be guessed from it. keystore.py stores only the SHA-256 hash of each key in keys.json. The key itself is random, shown once and saved in secrets/NAME.key. os.open with 0o600 makes a new file private from the first moment, and os.fchmod makes an old file private too (a file that exists keeps its old mode otherwise).
keystore.py
"""keystore.py: API keys of the clients. keys.json holds only hashes.
python3 keystore.py add CLIENT SCOPE make a key, save it in secrets/CLIENT.key (mode 600)
"""
import hashlib
import hmac
import json
import os
import secrets
import sys
from datetime import date, timedelta
def digest(key):
return hashlib.sha256(key.encode()).hexdigest()
def read_keys(path="keys.json"):
with open(path) as f:
return json.load(f)
def lookup(key, today, path="keys.json"):
"""Return the record of a key that is known and not expired, else None. A key stops working on its `expires` date."""
found = None
for record in read_keys(path)["keys"]: # no early exit: the time does not tell which one matched
if hmac.compare_digest(digest(key), record["hash"]):
found = record
return found if found and found["expires"] > today else None
def add_key(client, scopes, today, days=90, path="keys.json"):
"""Add a record with the hash of a new random key. Return the key: it is shown once and not stored."""
key = "kr_" + secrets.token_urlsafe(24)
data = read_keys(path) if os.path.exists(path) else {"keys": []}
number = 1 + sum(r["client"] == client for r in data["keys"])
data["keys"].append({"id": f"{client}-{number}", "client": client, "hash": digest(key), "scopes": scopes,
"created": today, "expires": (date.fromisoformat(today) + timedelta(days=days)).isoformat()})
with open(path, "w") as f:
json.dump(data, f, indent=1)
return key
def write_secret(path, text):
"""Write a file that only its owner can read: mode 600, whether the file is new or old."""
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
os.fchmod(fd, 0o600)
with os.fdopen(fd, "w") as f:
f.write(text + "\n")
if __name__ == "__main__" and sys.argv[1:2] == ["add"]:
os.makedirs("secrets", exist_ok=True)
client, scope = sys.argv[2], sys.argv[3]
write_secret(f"secrets/{client}.key", add_key(client, [scope], date.today().isoformat()))
print(f"key for {client} saved in secrets/{client}.key, hash saved in keys.json")2. Make the settings, two keys and a token
gateway.json holds the limits: 5 requests in 60 seconds for each key, and a body of at most 1024 bytes. The key of alpha has the scope predict, and the key of beta only read. The gateway and the service share the gateway token. umask 077 makes new files private to you. It runs in a subshell, ( ... ), and ends there.
cat > gateway.json <<'EOT'
{"rate": 5, "window": 60, "max_body": 1024}
EOT
python keystore.py add alpha predict
python keystore.py add beta read
( umask 077; python -c "import secrets; print(secrets.token_hex(16))" > secrets/gateway.token )
ls -l secretskey for alpha saved in secrets/alpha.key, hash saved in keys.json
key for beta saved in secrets/beta.key, hash saved in keys.json
total 12
-rw------- 1 you you 36 Nov 21 13:39 alpha.key
-rw------- 1 you you 36 Nov 21 13:39 beta.key
-rw------- 1 you you 33 Nov 21 13:39 gateway.token3. Save the gateway
ThreadingHTTPServer answers each request in its own thread. Authorization: Bearer KEY is the usual header for a key. Header names are case-insensitive (RFC 9110), so context writes each as Authorization. The scheme word (Bearer) is case-insensitive too, so authenticate accepts bearer. A 401 answer must say which scheme the client may use (RFC 9110), and the header for that is WWW-Authenticate, so authenticate sets WWW-Authenticate: Bearer on it. threading.Lock stops two threads from changing a counter at once.
gateway.py
"""gateway.py: the only door to the model service. It checks, counts, writes an audit line and forwards."""
import json
import os
import sys
import threading
import time
import urllib.error
import urllib.request
from datetime import date
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import keystore
CONFIG = {"rate": 5, "window": 60, "max_body": 1024} # gateway.json replaces these at start
SERVICE = os.environ.get("KR_SERVICE", "http://127.0.0.1:8421")
TOKEN = os.environ.get("KR_GATEWAY_TOKEN", "")
AUDIT, KEYS = "audit.log", "keys.json"
HITS, LOCK = {}, threading.Lock()
def route(ctx):
if ctx["path"] != "/predict":
return 404, "not found"
if ctx["method"] != "POST":
return 405, "use POST"
def authenticate(ctx):
auth = ctx["headers"].get("Authorization", "")
record = keystore.lookup(auth[7:], ctx["today"], KEYS) if auth[:7].lower() == "bearer " else None
if not record:
ctx["out"]["WWW-Authenticate"] = "Bearer"
return 401, "missing, unknown or expired key"
ctx["client"], ctx["key_id"] = record["client"], record["id"]
if "predict" not in record["scopes"]:
return 403, "this key may not call predict"
def limit_size(ctx):
if ctx["length"] > CONFIG["max_body"]:
return 413, f"body over {CONFIG['max_body']} bytes"
def limit_rate(ctx):
with LOCK:
hits = [t for t in HITS.get(ctx["key_id"], []) if ctx["now"] - t < CONFIG["window"]]
allowed = len(hits) < CONFIG["rate"]
if allowed:
hits.append(ctx["now"])
else:
ctx["out"]["Retry-After"] = str(int(CONFIG["window"] - (ctx["now"] - hits[0])) + 1)
HITS[ctx["key_id"]] = hits
if not allowed:
return 429, "too many requests"
STAGES = [route, authenticate, limit_size, limit_rate]
def context(method, path, headers, length, now=None, today=None):
"""What the stages need to know about one request. `out` holds headers for the answer."""
return {"method": method, "path": path, "length": length, "out": {},
"headers": {name.title(): value for name, value in headers.items()},
"now": time.monotonic() if now is None else now, "today": today or date.today().isoformat()}
def decide(ctx):
"""Run the stages in order. The first one that objects decides: (status, message)."""
for stage in STAGES:
verdict = stage(ctx)
if verdict:
return verdict
return 200, "allowed"
def audit(ctx, status, reason):
line = {"time": time.strftime("%Y-%m-%dT%H:%M:%S"), "client": ctx.get("client", "-"), "key": ctx.get("key_id", "-"),
"path": ctx["path"].split("?")[0][:40], "status": status, "reason": reason, "bytes": ctx["length"]}
with open(AUDIT, "a") as f:
f.write(json.dumps(line) + "\n")
def forward(ctx, body):
headers = {"Content-Type": ctx["headers"].get("Content-Type", ""), "X-Gateway-Token": TOKEN, "X-Client": ctx["client"]}
try:
with urllib.request.urlopen(urllib.request.Request(SERVICE + "/predict", body, headers), timeout=5) as r:
return r.status, r.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
except OSError:
return 502, b'{"error": "service unavailable"}'
class Handler(BaseHTTPRequestHandler):
server_version, sys_version = "kr-gateway", ""
timeout = 10 # a silent client cannot hold a thread for ever
def handle_one(self):
try:
length = max(0, int(self.headers.get("Content-Length") or 0))
except ValueError:
length = -1
ctx = context(self.command, self.path, self.headers, length)
status, reason = (400, "bad Content-Length") if length < 0 else decide(ctx)
if status == 200:
status, answer = forward(ctx, self.rfile.read(length))
reason = "forwarded"
else:
answer = json.dumps({"error": reason}).encode()
audit(ctx, status, reason)
self.send_response(status)
for name, value in ctx["out"].items():
self.send_header(name, value)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(answer)))
self.end_headers()
self.wfile.write(answer)
do_GET = do_POST = do_PUT = do_DELETE = handle_one
def log_message(self, *args):
pass
def load_config(path="gateway.json"):
with open(path) as f:
CONFIG.update(json.load(f))
if not all(isinstance(CONFIG.get(k), int) and CONFIG[k] > 0 for k in ("rate", "window", "max_body")):
sys.exit("gateway.json needs positive numbers for rate, window and max_body")
if __name__ == "__main__":
if not TOKEN:
sys.exit("set KR_GATEWAY_TOKEN first")
load_config()
server = ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1]) if len(sys.argv) > 1 else 8420), Handler)
print("gateway ready, stages:", [s.__name__ for s in STAGES], file=sys.stderr, flush=True)
server.serve_forever()The rate limit keeps the times of the last requests of each key and refuses a request when rate of them are inside the window. Retry-After says how many seconds remain until the oldest one leaves it.
4. Save the tests and run them
test_gateway.py makes a temporary key store (one key is expired) and a made-up clock. call runs one made-up request through the stages. A table lists what differs from a good request and the status that must come back. The rate test sends 20 requests and counts the answers, and one test checks that no query string reaches the audit log. Step 5 proves "only the gateway may call the service" on the running programs. Open the block and save the file.
The finished file: test_gateway.py
test_gateway.py
"""test_gateway.py: prove each control of the gateway."""
import os
import tempfile
import unittest
from datetime import date
import gateway
import keystore
TODAY, START, WORK = "2026-11-30", date.today().isoformat(), tempfile.mkdtemp()
gateway.KEYS = os.path.join(WORK, "keys.json")
KEYS = {"alpha": keystore.add_key("alpha", ["predict"], START, path=gateway.KEYS),
"beta": keystore.add_key("beta", ["read"], START, path=gateway.KEYS),
"old": keystore.add_key("old", ["predict"], "2026-01-01", path=gateway.KEYS)} # ended 2026-04-01
gateway.CONFIG.update(rate=5, window=60, max_body=1024)
def call(key="alpha", method="POST", path="/predict", length=10, now=1000.0, headers=None):
"""Run one made-up request through the stages: return its status."""
headers = headers if headers is not None else {"Authorization": "Bearer " + KEYS.get(key, key)}
return gateway.decide(gateway.context(method, path, headers, length, now=now, today=TODAY))[0]
TABLE = [ # (name, what differs from a good request, status that the gateway must return)
("valid key", {}, 200),
("lower-case header name", {"headers": {"authorization": "Bearer " + KEYS["alpha"]}}, 200),
("lower-case scheme", {"headers": {"Authorization": "bearer " + KEYS["alpha"]}}, 200),
("no key", {"headers": {}}, 401),
("unknown key", {"key": "kr_guess"}, 401),
("expired key", {"key": "old"}, 401),
("key without predict scope", {"key": "beta"}, 403),
("body of 5000 bytes", {"length": 5000}, 413),
("wrong path", {"path": "/admin"}, 404),
("wrong method", {"method": "GET"}, 405),
]
class GatewayTests(unittest.TestCase):
def setUp(self):
gateway.HITS.clear()
def test_table(self):
for name, change, want in TABLE:
with self.subTest(name):
gateway.HITS.clear()
self.assertEqual(call(**change), want)
def test_rate_limit_counts_each_key(self):
sent = [call(now=1000.0 + i) for i in range(20)]
self.assertEqual((sent.count(200), sent.count(429)), (5, 15))
self.assertEqual(call(now=1061.0), 200) # the window has passed
def test_audit_line_has_no_query_string(self):
gateway.AUDIT = os.path.join(WORK, "audit.log")
gateway.audit(gateway.context("POST", "/predict?key=kr_abc", {}, 10), 404, "not found")
with open(gateway.AUDIT) as f:
self.assertNotIn("kr_abc", f.read())
if __name__ == "__main__":
for name, change, want in TABLE:
gateway.HITS.clear()
print(f"{call(**change)} {name}")
unittest.main(argv=["test_gateway"])python -u test_gateway.py200 valid key
200 lower-case header name
200 lower-case scheme
401 no key
401 unknown key
401 expired key
403 key without predict scope
413 body of 5000 bytes
404 wrong path
405 wrong method
...
----------------------------------------------------------------------
Ran 3 tests in 0.004s
OK5. Start both programs and call them
Only the gateway may call the service. The service checks the gateway token, and the gateway checks the key. This step tries both doors.
- Client alpha → Gateway: POST /predict with a key
- Gateway → Key store: is the key known, in scope?
- Gateway → Model service: forward with gateway token
- Attacker → Model service: direct call, no token: 401
export hands the token to the next programs.
export KR_GATEWAY_TOKEN=$(cat secrets/gateway.token)
python service.py 8421 2> service.log > /dev/null &
echo $! > service.pid
python gateway.py 8420 2> gateway.log > /dev/null &
echo $! > gateway.pid
sleep 1
KEY=$(cat secrets/alpha.key)
BODY='{"failed": 5, "new_device": 1, "km": 100}'
curl -s -w ' %{http_code}\n' -X POST -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d "$BODY" http://127.0.0.1:8420/predict{"model": "v1", "score": 0.8, "label": "suspicious"} 200$KEY keeps the key out of your shell history. Now three calls that must fail: the service with no token, the gateway with the key of beta, and the gateway with no key.
curl -s -w ' %{http_code}\n' -X POST -H 'Content-Type: application/json' -d "$BODY" http://127.0.0.1:8421/predict
curl -s -w ' %{http_code}\n' -X POST -H "Authorization: Bearer $(cat secrets/beta.key)" -H 'Content-Type: application/json' -d "$BODY" http://127.0.0.1:8420/predict
curl -s -w ' %{http_code}\n' -X POST -H 'Content-Type: application/json' -d "$BODY" http://127.0.0.1:8420/predict{"error": "caller not allowed"} 401
{"error": "this key may not call predict"} 403
{"error": "missing, unknown or expired key"} 4016. Hit the rate limit and read the audit log
One of the five requests is used. Send seven more. -o /dev/null drops the body. -i adds the response headers.
for i in 1 2 3 4 5 6 7; do curl -s -o /dev/null -w '%{http_code} ' -X POST -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d "$BODY" http://127.0.0.1:8420/predict; done; echo
curl -s -i -X POST -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d "$BODY" http://127.0.0.1:8420/predict | grep -i -E '^HTTP|retry-after'200 200 200 200 429 429 429
HTTP/1.0 429 Too Many Requests
Retry-After: 60Five requests passed in all, and the next three got 429. The audit log has one JSON line for each request, and never the key or the body. The call that went straight to the service is not in it: one more reason to let nobody call it directly.
head -2 audit.log
kill $(cat gateway.pid) $(cat service.pid){"time": "2026-11-21T13:50:54", "client": "alpha", "key": "alpha-1", "path": "/predict", "status": 200, "reason": "forwarded", "bytes": 41}
{"time": "2026-11-21T13:50:54", "client": "beta", "key": "beta-1", "path": "/predict", "status": 403, "reason": "this key may not call predict", "bytes": 41}Your turn
Extend TABLE in test_gateway.py with four rows, and add one test. Each row says what differs from a good request, like {"method": "GET"}. Predict each status before you run the file.
- The method
PUT, with a valid key. - The header
Authorization: Basic abc(another scheme) in place ofBearer. - A body length of exactly 1024 bytes.
- A body length of 1025 bytes.
- A test
test_rate_limit_of_three: setgateway.CONFIG["rate"] = 3and send 20 requests in the same second, as the existing rate test does. Undo the change after the test withself.addCleanup(gateway.CONFIG.update, rate=5), so that no other test sees it.
Check yourself
The key of beta gets 403 and an unknown key gets 401. Why two codes?
401 says "I do not know who you are". 403 says "I know who you are, and you may not do this". The audit log can then tell a client that oversteps from a stranger.
Why does the rate limit count per key and not per source address?
The key names the responsible client, and the limit protects the capacity that each team was promised. Many clients can share one address.
What happens to the counters when the gateway restarts, or with two gateways?
They live in one process. A restart gives every client a fresh window, and two gateways each allow the full rate. A real gateway keeps them in a shared store such as Redis.
Field notes
- TLS is not in this lab (everything is on loopback). A real gateway ends TLS in front of the clients, and the traffic to the service needs TLS or a private network. "Networking hands-on" built certificates.
- A managed API gateway gives you keys, limits, TLS and logs as settings. Test it the same way.
- Give an unknown and an expired key the same 401 text, so that nobody learns which keys existed.
- Count tokens as well as requests for an LLM service (lesson 8).
- This gateway limits a key only after the key is known. A flood of bad keys is never limited, and each request still adds a line to
audit.log, which has no size limit. Throttle before authentication too (per source address, or at the platform edge), and rotate the audit log, or the flood fills the disk.