Lesson 09 · 45 minutes
Write access rules for the model service as code and test them
- Write access rules as data that say who may call which model, from where, with which data class
- Evaluate a request against the rules with default deny and deny-wins
- Test the rules with a table of requests and report the denied ones
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 partner company wants to call the model, and a second team wants to send it data marked "internal". The rules live in three places today: in the head of one platform engineer, an email, and an if that someone added to the gateway. Your lead says: "I want one file that says who may do what, and a table of requests that proves it. When I ask 'may team beta send internal data?', a test answers, not a person."
Recall
Lesson 8: which stage runs first when KR_EXTRA=budget is set, the load stage or the budget stage, and why?
The load stage. A request that is shed must not be charged to the client's budget.
Lesson 3: what does a stage return when it lets a request go on?
Nothing (None). A stage that objects returns a status and a reason, and decide stops.
The idea
Policy as code means that the rules about access are data or code in a file, in version control, reviewed like any change, and tested. The question "may this happen?" then has an answer that a program gives, the same every time.
Our rules answer one question with four facts: who (the client), what (the model), from where (the caller's network address) and with which data (a class, public, internal or secret, sent in the header X-Data-Class). Two design rules keep the file safe:
| Rule | Meaning |
|---|---|
| Default deny | A request that no rule allows is denied. A missing rule is never an opening. |
| Deny wins | If a deny rule and an allow rule both match, the answer is deny. |
The evaluator is the policy decision point: it answers allow or deny. The gateway stage is the policy enforcement point: it asks and obeys. Apart, you can test the decisions without a network.
- Client → Gateway: request, key, data class
- Gateway → Policy: client, model, source, data
- Policy → Gateway: allow or deny, and which rule
- Gateway → Service: allow: forward the request
- Gateway → Client: deny: 403 and the reason
A real platform uses a policy engine for this job, such as Open Policy Agent (language: Rego) or Cedar. The method carries over: rules as data, default deny, a table of test requests.
Policy decides who may call the model. It does not protect the data while the model computes. In transit TLS protects it, and at rest encryption of the disk does, but in use the data is plain in memory, because the program must read it (lesson 4, step 2 read a secret out of a running process). Three approaches protect data in use, and the lab cannot run them:
- Confidential computing runs the work in a hardware-based trusted execution environment (TEE) that keeps code outside it from the data. Attestation proves to the sender which hardware and code run inside. It needs supported hardware and trust in its maker, and a side-channel attack, which learns secrets from timing or power use, remains a risk.
- Homomorphic encryption computes on encrypted data: decrypting the result gives the result on the plain data.
- Secure multi-party computation lets several parties compute over their inputs while none reveals its input to the others.
A team asks for one when secret data must run on a machine that someone else operates. On your own hardened host, the controls of this course are the answer: a separate user, this policy, and a denied secret class.
Worked example
1. Write the rules
Each rule has an id (so that a decision can say which rule decided), an effect, and the four facts:
from is a list of networks in CIDR form. The number after the slash says how many of the 32 bits of an address must match: 10.0.0.0/8 is every address that starts with 10, 192.0.2.0/24 every address that starts with 192.0.2, and 0.0.0.0/0 every address. 127.0.0.0/8 is your own computer. "*" as the client means every client.
In this lab every source is 127.0.0.1 and there is one model, so from and model are tested on the table (steps 3 and 4), not on the running gateway. The key of beta has the scope read, so it stops at authenticate, before the policy.
policy.json
{"rules": [
{"id": "alpha-app", "effect": "allow", "client": "alpha", "model": "login-risk", "from": ["127.0.0.0/8", "10.0.0.0/8"], "data": ["public", "internal", "secret"]},
{"id": "beta-batch", "effect": "allow", "client": "beta", "model": "login-risk", "from": ["10.0.0.0/8"], "data": ["public"]},
{"id": "no-secret-data", "effect": "deny", "client": "*", "model": "login-risk", "from": ["0.0.0.0/0"], "data": ["secret"]}
]}2. Save the evaluator
matches checks one rule against one request. ipaddress is the standard module for addresses: ip_address(x) in ip_network(n) asks whether an address is inside a network. evaluate applies deny-wins and default deny. check_policy is the gateway stage. The command line prints one line for each request, and a report of the denied ones.
policy.py
"""policy.py: access rules as data, and an evaluator. The gateway loads it with KR_EXTRA=policy.
python3 policy.py policy.json cases.json print each decision, then the denied requests
"""
import ipaddress
import json
import sys
from collections import Counter
MODEL = "login-risk" # the one model that this service serves
RULES = []
def matches(rule, request):
return (rule["client"] in ("*", request["client"]) and rule["model"] == request["model"]
and request["data"] in rule["data"]
and any(ipaddress.ip_address(request["source"]) in ipaddress.ip_network(net) for net in rule["from"]))
def evaluate(rules, request):
"""(allowed, reason). A matching deny rule wins. No matching rule means deny."""
hits = [r for r in rules if matches(r, request)]
for rule in hits:
if rule["effect"] == "deny":
return False, f"denied by {rule['id']}"
return (True, f"allowed by {hits[0]['id']}") if hits else (False, "no rule allows this")
def failed_cases(rules, cases):
"""The cases where the policy decides other than "expect"."""
return [c for c in cases if evaluate(rules, c["request"])[0] != (c["expect"] == "allow")]
def check_policy(ctx):
request = {"client": ctx["client"], "model": MODEL, "source": ctx["source"], "data": ctx["headers"].get("X-Data-Class", "")}
allowed, reason = evaluate(RULES, request)
if not allowed:
return 403, "policy: " + reason
def install(stages, config, path="policy.json"):
with open(path) as f:
RULES.extend(json.load(f)["rules"])
stages.append(check_policy)
if __name__ == "__main__":
with open(sys.argv[1]) as f, open(sys.argv[2]) as g:
rules, cases = json.load(f)["rules"], json.load(g)
denied, wrong = Counter(), 0
for number, case in enumerate(cases, 1):
request = case["request"]
allowed, reason = evaluate(rules, request)
note = "" if allowed == (case["expect"] == "allow") else f" WRONG: expected {case['expect']}"
wrong += bool(note)
print(f"{number:2} {'allow' if allowed else 'DENY '} {request['client']:6} {request['model']:13} {request['data']:9} {request['source']:12} {reason}{note}")
if not allowed:
denied[(request["client"], reason)] += 1
print(f"{sum(denied.values())} of {len(cases)} requests denied, {wrong} decided other than expected")
for (client, reason), count in sorted(denied.items()):
print(f" {client}: {count} x {reason}")
sys.exit(1 if wrong else 0)3. Test it with a table
test_policy.py holds its own small set of rules, so that it tests the evaluator and not your edits of policy.json. Rule a allows all three data classes, so a secret request from an allowed client matches both a and d. Only "deny wins" refuses it.
test_policy.py
"""test_policy.py: tests for the policy evaluator, on a table of requests."""
import unittest
import policy
RULES = [{"id": "a", "effect": "allow", "client": "alpha", "model": "login-risk", "from": ["10.0.0.0/8"], "data": ["public", "internal", "secret"]},
{"id": "d", "effect": "deny", "client": "*", "model": "login-risk", "from": ["0.0.0.0/0"], "data": ["secret"]}]
ASK = lambda client="alpha", source="10.1.1.1", data="public", model="login-risk": {"client": client, "model": model, "source": source, "data": data}
TABLE = [ # (name, request, allowed?)
("a rule allows it", ASK(), True),
("other data class", ASK(data="internal"), True),
("source outside the network", ASK(source="192.0.2.1"), False),
("client without a rule", ASK(client="gamma"), False),
("other model", ASK(model="report-writer"), False),
("a deny rule beats an allow rule", ASK(data="secret"), False),
("no data class given", ASK(data=""), False),
]
class PolicyTests(unittest.TestCase):
def test_table(self):
for name, request, want in TABLE:
with self.subTest(name):
self.assertEqual(policy.evaluate(RULES, request)[0], want)
def test_deny_wins_over_an_allow_rule(self):
self.assertEqual(policy.evaluate(RULES, ASK(data="secret")), (False, "denied by d"))
def test_empty_policy_denies_everything(self):
self.assertEqual(policy.evaluate([], ASK()), (False, "no rule allows this"))
def test_failed_cases(self):
good, wrong = {"request": ASK(), "expect": "allow"}, {"request": ASK(), "expect": "deny"}
self.assertEqual(policy.failed_cases(RULES, [good, wrong]), [wrong])
if __name__ == "__main__":
unittest.main()python test_policy.py...
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK4. Run the table of the lab
policy-cases.json lists requests, each with an expect of allow or deny. The report says how many requests were denied, and for which reason. It exits with 1 when a decision differs from the expectation.
policy-cases.json
[
{"request": {"client": "alpha", "model": "login-risk", "source": "127.0.0.1", "data": "internal"}, "expect": "allow"},
{"request": {"client": "alpha", "model": "login-risk", "source": "10.2.3.4", "data": "public"}, "expect": "allow"},
{"request": {"client": "alpha", "model": "login-risk", "source": "203.0.113.9", "data": "public"}, "expect": "deny"},
{"request": {"client": "alpha", "model": "login-risk", "source": "127.0.0.1", "data": "secret"}, "expect": "deny"},
{"request": {"client": "beta", "model": "login-risk", "source": "10.9.9.9", "data": "public"}, "expect": "allow"},
{"request": {"client": "beta", "model": "login-risk", "source": "10.9.9.9", "data": "internal"}, "expect": "deny"},
{"request": {"client": "beta", "model": "report-writer", "source": "10.9.9.9", "data": "public"}, "expect": "deny"},
{"request": {"client": "gamma", "model": "login-risk", "source": "127.0.0.1", "data": "public"}, "expect": "deny"}
]python policy.py policy.json policy-cases.json
echo "exit code $?" 1 allow alpha login-risk internal 127.0.0.1 allowed by alpha-app
2 allow alpha login-risk public 10.2.3.4 allowed by alpha-app
3 DENY alpha login-risk public 203.0.113.9 no rule allows this
4 DENY alpha login-risk secret 127.0.0.1 denied by no-secret-data
5 allow beta login-risk public 10.9.9.9 allowed by beta-batch
6 DENY beta login-risk internal 10.9.9.9 no rule allows this
7 DENY beta report-writer public 10.9.9.9 no rule allows this
8 DENY gamma login-risk public 127.0.0.1 no rule allows this
5 of 8 requests denied, 0 decided other than expected
alpha: 1 x denied by no-secret-data
alpha: 1 x no rule allows this
beta: 2 x no rule allows this
gamma: 1 x no rule allows this
exit code 0Request 4 matches an allow rule (alpha-app lists secret) and a deny rule, and the deny rule wins. The other denied requests match no rule at all. A rule at work and a missing rule are different events: the second can be a client that needs a rule, or a probe.
5. Enforce it in the gateway
The policy stage needs the address of the caller: context gets a source, which the handler fills from the connection (self.client_address[0]). Every other line is as in lesson 8. Replace gateway.py with the finished file.
The finished file: gateway.py
gateway.py
"""gateway.py: the only door to the model service. It checks, counts, writes an audit line and forwards."""
import importlib
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, INFLIGHT, LOCK = {}, [0], threading.Lock() # INFLIGHT[0] counts the requests that are being served now
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, source="127.0.0.1", now=None, today=None, inflight=None):
"""What the stages need to know about one request. `out` holds headers for the answer."""
return {"method": method, "path": path, "length": length, "source": source, "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(),
"inflight": INFLIGHT[0] if inflight is None else inflight}
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"]}
with LOCK:
INFLIGHT[0] += 1
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"}'
finally:
with LOCK:
INFLIGHT[0] -= 1
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, self.client_address[0])
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()
for name in filter(None, os.environ.get("KR_EXTRA", "").split(",")):
importlib.import_module(name).install(STAGES, 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()Start both programs with the policy stage, and call with three data classes (-H adds a header).
export KR_GATEWAY_TOKEN=$(cat secrets/gateway.token)
python service.py 8421 2> service.log > /dev/null &
echo $! > service.pid
KR_EXTRA=policy python gateway.py 8420 2> gateway.log > /dev/null &
echo $! > gateway.pid
sleep 1
KEY=$(cat secrets/alpha.key)
for CLASS in internal secret none; do
curl -s -w ' %{http_code}\n' -X POST -H "Authorization: Bearer $KEY" -H "X-Data-Class: $CLASS" -H 'Content-Type: application/json' -d '{"failed": 1, "new_device": 0, "km": 5}' http://127.0.0.1:8420/predict
done
tail -2 audit.log
kill $(cat gateway.pid) $(cat service.pid){"model": "v1", "score": 0.0, "label": "normal"} 200
{"error": "policy: denied by no-secret-data"} 403
{"error": "policy: no rule allows this"} 403
{"time": "2026-11-21T13:54:05", "client": "alpha", "key": "alpha-1", "path": "/predict", "status": 403, "reason": "policy: denied by no-secret-data", "bytes": 39}
{"time": "2026-11-21T13:54:05", "client": "alpha", "key": "alpha-1", "path": "/predict", "status": 403, "reason": "policy: no rule allows this", "bytes": 39}internal passes, secret is denied by the deny rule, and none, a class that no rule names, is denied by default. The audit line records the reason.
Your turn
A partner, gamma, needs the model. It may call login-risk only from the network 192.0.2.0/24 and only with public data. Save the table of the partner's requests, with the answer that each should get.
cases-partner.json
[
{"request": {"client": "gamma", "model": "login-risk", "source": "192.0.2.10", "data": "public"}, "expect": "allow"},
{"request": {"client": "gamma", "model": "login-risk", "source": "192.0.2.10", "data": "internal"}, "expect": "deny"},
{"request": {"client": "gamma", "model": "login-risk", "source": "198.51.100.7", "data": "public"}, "expect": "deny"},
{"request": {"client": "gamma", "model": "report-writer", "source": "192.0.2.10", "data": "public"}, "expect": "deny"},
{"request": {"client": "alpha", "model": "login-risk", "source": "127.0.0.1", "data": "internal"}, "expect": "allow"},
{"request": {"client": "alpha", "model": "login-risk", "source": "127.0.0.1", "data": "secret"}, "expect": "deny"},
{"request": {"client": "beta", "model": "login-risk", "source": "10.5.5.5", "data": "public"}, "expect": "allow"},
{"request": {"client": "beta", "model": "login-risk", "source": "10.5.5.5", "data": "internal"}, "expect": "deny"},
{"request": {"client": "delta", "model": "login-risk", "source": "127.0.0.1", "data": "public"}, "expect": "deny"},
{"request": {"client": "gamma", "model": "login-risk", "source": "192.0.2.99", "data": "public"}, "expect": "allow"}
]Run python policy.py policy.json cases-partner.json. Then add a rule for gamma to policy.json, with a clear id, until no decision differs from the expectation.
Check yourself
Why is "deny wins" safer than "the first rule that matches decides"?
With first match, the order decides, and an allow rule added above a deny rule opens a hole unnoticed. With deny wins, a deny rule holds whatever else is in the file.
The policy file has a mistake that allows too much. Which control catches it before it reaches production?
The table of test requests, run in the build, with cases that must be denied: a wrong network, a wrong data class, an unknown client, another model. A table of only allowed cases tests nothing. The readiness check of lesson 10 runs it.
The gateway takes the data class from a header that the client writes. What is the weakness?
A client can claim any class. The owner of the data must set it, for example in a trusted upstream system that signs the request. Until then the rule holds only for honest clients, and the audit log should record the claimed class.
A partner wants to send `secret` records to your model on a cloud provider's machine. Traffic and disk are encrypted. What is still open, and what do you ask for?
The data in use: it is plain in memory, which the provider's software and staff can reach. Ask whether the model can run in a TEE, with attestation that you verify before sending, and weigh the cost (hardware, trust in its maker, side channels). If not, keep secret data off that host, as this policy does.
Field notes
- Keep policy in its own file and review path: a change to who may call a model needs a second person.
- Write a case for every rule, several that must be denied, and one for every incident: the request that should have been denied becomes a permanent test. Log the id of the rule that decided, so that a complaint has a one-line answer.
- Data in use costs something. A TEE usually costs a small to moderate slowdown that depends on the workload and the hardware. Homomorphic encryption is much slower, often by orders of magnitude for general programs. No source gives one figure for every workload, so measure on your own model. Take the current text from the Confidential Computing Consortium's "A Technical Analysis of Confidential Computing" and from the NIST pages on privacy-enhancing cryptography.
- A source address is only as good as the path to it: behind a load balancer the source is the balancer, and
X-Forwarded-Forcan be forged. An IPv6 address never matches an IPv4 network, so a deny rule for0.0.0.0/0does not cover it: add::/0, or refuse IPv6.