Lesson 10 · 50 minutes
Build a secure notes API and prove every control
- Combine authentication, an owner check, validation, limits and safe logging in one program
- Write requests that must be refused and run them as a test
- Show that the test fails when a control is removed
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
Your team is about to release a notes API, and the release manager asks: "How do I know that it is safe?" "We read the code" is not an answer that a manager can check. Your task is to build the API with the controls of lessons 2, 3, 4, 5 and 7, write a test that sends each bad request and expects a refusal, show that the test fails when a control is removed, and then add one more rule to the API and to the test yourself.
Recall
Lesson 5. Why does every query of this API use "?" and never a joined string?
A joined string lets the user's text become part of the SQL. A ? keeps the value apart from the code, so the database reads it only as data.
Lesson 7. A request has a valid key, but it comes too fast. Which status does the server answer, and which lesson-7 object decides it?
429 Too Many Requests. The token bucket decides: each request takes a token, an empty bucket means a refusal, and the bucket refills at a fixed rate.
The idea
notes_api.py joins the controls of lessons 2, 3 (the API key), 4, 5 and 7. It has no session cookie and no fetch feature, so lessons 3 (cookie) and 6 are not part of it. It refuses a bad request as early as it can: API key (401), rate limit (429), body size (413, 400), route allowlist (404), validation (415, 400), then the owner check inside the SQL query (404). Last comes 405: a method that the note route does not know. Every query uses ? placeholders, and the log never holds a key.
- Request → API key: X-API-Key header
- API key → Rate limit: key is known, else 401
- Rate limit → Body size: a token is left, else 429
- Body size → Route: length is sane, else 413 or 400
- Route → Validation: path is allowed, else 404
- Validation → Owner check: type and text fit, else 415 or 400
- Owner check → Answer: owner is in the SQL, else 404
Worked example
1. Make two keys
Each user gets one key from the environment.
- Alice → Notes API: requests with ALICE_KEY
- Bob → Notes API: requests with BOB_KEY
- Notes API → notes.db: queries with owner = ?
cd ~/krlab/web-apis
export ALICE_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")
export BOB_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")
rm -f notes.db2. Write the API
Create notes_api.py. Find each control in it. These names are new:
- The notes now live in a SQLite file,
notes.db, so they survive a restart. PRIMARY KEYmarks the column that names each row, andAUTOINCREMENTmakes the database number the rows.NOT NULLrefuses an empty value, andIF NOT EXISTSskips the creation when the table is already there.commitsaves a change.UPDATE notes SET text = ? WHERE ...changes a row, andDELETE FROM notes WHERE ...removes it. Lesson 5 explainedINSERTandSELECT.run(sql, *args)takes any number of values aftersqland gathers them inargs. A comprehension is a loop written inside brackets that builds a list or a dictionary:[{"id": i, "text": t} for i, t in rows]makes one small dictionary for each row.re.compile(...)builds a pattern once, and.fullmatch(path)applies it to the whole path. The linedo_GET = do_POST = ... = handle_requestmakes one method serve all five HTTP methods, andself.commandholds the method of the request.cur.lastrowidis the id of the row that has been added, andfetchonereturns the first row of a result.A if c else BgivesAwhencis true andBwhen not, sotokens - 1 if tokens >= 1 else tokenstakes one token only when there is one, and413 if size > MAX_BODY else 400picks the status.user = "-"inside the class is a default thatlog_requestprints until the key is known.- The status
405 Method Not Allowedmeans that the path exists but not for this method. - A bad
Content-Length(not a number, or below 0) gets400. Without that check,readwith a negative size would wait for ever, and one request would block the whole server.
notes_api.py
import hmac, json, os, re, sqlite3, time
from http.server import BaseHTTPRequestHandler, HTTPServer
KEYS = {name: os.environ[name.upper() + "_KEY"] for name in ("alice", "bob")}
MAX_BODY = 1024
ROUTE = re.compile(r"/notes(?:/([0-9]{1,9}))?")
db = sqlite3.connect("notes.db")
db.execute("CREATE TABLE IF NOT EXISTS notes "
"(id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, text TEXT NOT NULL)")
def run(sql, *args):
cur = db.execute(sql, args)
db.commit()
return cur
buckets = {name: (10, time.monotonic()) for name in KEYS} # (tokens, last time)
def allow(name): # token bucket: 2 requests a second, burst of 10
tokens, last = buckets[name]
now = time.monotonic()
tokens = min(10, tokens + (now - last) * 2)
buckets[name] = (tokens - 1 if tokens >= 1 else tokens, now)
return tokens >= 1
class Handler(BaseHTTPRequestHandler):
user = "-"
def reply(self, status, obj=None):
data = json.dumps(obj).encode() if obj is not None else b""
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_request(self, code="-", size="-"):
self.log_message("%s %s %s user=%s", self.command, self.path.split("?")[0], code, self.user)
def authenticate(self):
key = self.headers.get("X-API-Key", "").encode()
for name, known in KEYS.items():
if hmac.compare_digest(key, known.encode()):
return name
def read_text(self, size):
if self.headers.get_content_type() != "application/json":
return self.reply(415, {"error": "send application/json"})
try:
text = json.loads(self.rfile.read(size))["text"]
except (ValueError, KeyError, TypeError):
return self.reply(400, {"error": "body must be JSON with a text field"})
if not isinstance(text, str) or not 1 <= len(text) <= 200:
return self.reply(400, {"error": "text must be 1 to 200 characters"})
return text
def handle_request(self):
name = self.authenticate()
if name is None:
return self.reply(401, {"error": "not authenticated"})
self.user = name
if not allow(name):
return self.reply(429, {"error": "slow down"})
try:
size = int(self.headers.get("Content-Length") or 0)
except ValueError:
size = -1
if not 0 <= size <= MAX_BODY:
return self.reply(413 if size > MAX_BODY else 400, {"error": "bad or large Content-Length"})
match, method = ROUTE.fullmatch(self.path), self.command
if not match:
return self.reply(404, {"error": "not found"})
text = None
if method in ("POST", "PUT"):
text = self.read_text(size)
if text is None:
return
if match[1] is None: # /notes
if method == "GET":
rows = run("SELECT id, text FROM notes WHERE owner = ?", name)
return self.reply(200, [{"id": i, "text": t} for i, t in rows])
if method == "POST":
cur = run("INSERT INTO notes (owner, text) VALUES (?, ?)", name, text)
return self.reply(201, {"id": cur.lastrowid, "text": text})
else: # /notes/<id>
nid = int(match[1])
row = run("SELECT text FROM notes WHERE id = ? AND owner = ?", nid, name).fetchone()
if row is None: # missing, or not yours
return self.reply(404, {"error": "no such note"})
if method == "GET":
return self.reply(200, {"id": nid, "text": row[0]})
if method == "DELETE":
run("DELETE FROM notes WHERE id = ? AND owner = ?", nid, name)
return self.reply(204)
if method == "PUT":
run("UPDATE notes SET text = ? WHERE id = ? AND owner = ?", text, nid, name)
return self.reply(200, {"id": nid, "text": text})
self.reply(405, {"error": "method not allowed"})
do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = handle_request
HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()3. Write the test
Create test_api.sh. It is a shell script. Four parts need a word:
checktakes a label, the expected status and then the arguments forcurl, and it prints PASS or FAIL. It is the function of lesson 8. In the lineunknown method,-X PATCHsets the HTTP method.- The loop sends 40 requests (
seq 40counts from 1 to 40) and counts the answers429inrefused. It passes when there is at least one. On any normal machine the 40 requests take about a second, while the bucket holds only 10 tokens and refills at 2 a second, so some requests are refused. -m 3stops curl after 3 seconds, because a server that waits for a body that never comes would hang the test.grep -qF -- "$ALICE_KEY" server.logsearches the log without printing (-q) for plain text (-F). The--ends the options: a key can start with-, and without--grep would read it as an option and let the test pass by mistake.
The line quote in the text sends a note with an apostrophe. A query joined from strings would break on it, so the server would send no answer and the test would fail; with ? the text is stored as it is. (The line SQL in the id shows only that the route pattern refuses a bad path.) Most lines must be refused; the 201 and 200 lines prove that good requests work.
test_api.sh
H=http://127.0.0.1:8300
J='Content-Type: application/json'
A="X-API-Key: $ALICE_KEY"; B="X-API-Key: $BOB_KEY"
check() { # label, expected status, curl arguments
got=$(curl -s -o /dev/null -w '%{http_code}' "${@:3}")
[ "$got" = "$2" ] && echo "PASS $2 $1" || { echo "FAIL $1: wanted $2, got $got"; FAILED=1; }
}
check "no key" 401 $H/notes
check "alice creates" 201 -H "$A" -H "$J" -d '{"text":"alice secret"}' $H/notes
check "bob creates" 201 -H "$B" -H "$J" -d '{"text":"bob secret"}' $H/notes
check "alice reads own" 200 -H "$A" $H/notes/1
check "alice reads bob's" 404 -H "$A" $H/notes/2
check "alice deletes bob's" 404 -H "$A" -X DELETE $H/notes/2
check "SQL in the id" 404 -H "$A" "$H/notes/1%20OR%201=1"
check "quote in the text" 201 -H "$B" -H "$J" -d "{\"text\":\"bob's note\"}" $H/notes
check "empty text" 400 -H "$A" -H "$J" -d '{"text":""}' $H/notes
check "wrong type" 415 -H "$A" -d '{"text":"x"}' $H/notes
check "big body" 413 -H "$A" -H "$J" -d "{\"text\":\"$(head -c 2000 /dev/zero | tr '\0' a)\"}" $H/notes
check "key in the URL" 404 -H "$A" "$H/nope?key=$ALICE_KEY"
check "negative length" 400 -H "$B" -H "$J" -H 'Content-Length: -1' -d x -m 3 $H/notes
check "unknown method" 405 -H "$B" -X PATCH $H/notes/2
refused=0
for i in $(seq 40); do
[ "$(curl -s -o /dev/null -w '%{http_code}' -H "$B" $H/notes)" = 429 ] && refused=$((refused+1))
done
[ "$refused" -ge 1 ] && echo "PASS 429 rate limit" || { echo "FAIL rate limit: no 429 in 40 requests"; FAILED=1; }
grep -qF -- "$ALICE_KEY" server.log && { echo "FAIL key in log"; FAILED=1; } || echo "PASS no key in log"
exit ${FAILED:-0}4. Run the real test
Start the server with its log in a file (2> server.log sends the error output, where the server writes its log, to that file). SERVER=$! saves the process number of the background server, so that kill $SERVER can stop it later. Then run the test.
python3 notes_api.py 2> server.log &
SERVER=$!
sleep 1
bash test_api.shPASS 401 no key
PASS 201 alice creates
PASS 201 bob creates
PASS 200 alice reads own
PASS 404 alice reads bob's
PASS 404 alice deletes bob's
PASS 404 SQL in the id
PASS 201 quote in the text
PASS 400 empty text
PASS 415 wrong type
PASS 413 big body
PASS 404 key in the URL
PASS 400 negative length
PASS 405 unknown method
PASS 429 rate limit
PASS no key in logNo FAIL. Stop the server with kill $SERVER. If many lines say FAIL, run cat server.log: the line Address already in use means that an old server still holds port 8300. Stop the old one (lesson 0 shows the command that lists the ports in use) and run the test again on a fresh notes.db.
5. Remove a control and watch the test fail
A test that cannot fail proves nothing. sed edits text: the command below copies notes_api.py to weak.py with a much larger size limit. Test the copy.
sed 's/MAX_BODY = 1024/MAX_BODY = 10**6/' notes_api.py > weak.py
rm -f notes.db
python3 weak.py 2> server.log &
SERVER=$!
sleep 1
bash test_api.sh | grep -v PASS
kill $SERVERFAIL big body: wanted 413, got 400The test caught the change. (The 200-character check still refused the text, with a 400.) Delete weak.py and notes.db.
Your turn
The release manager adds a rule: no user may keep more than 3 notes, because storage costs money. Add it to your own notes_api.py and to your own test. There are no steps here.
- In the code, a
POST /notesfrom a user who already owns 3 notes is refused with status 409 (Conflict). Count the notes with a query that uses a?, like the other queries. - Stop the server, delete
notes.db, set the two keys again if your terminal is new, and start the server. - As alice, create four notes in a row and read the status of each. List alice's notes. As bob, create one note. As alice, delete note 1 and create one more note.
- Write a second script,
test_quota.sh, that uses the samecheckfunction and tests the fourth note, so that the rule is tested for good. Run it on a fresh server. (Do not add the lines totest_api.sh: that script already uses most of the burst of alice, and a 429 would hide the result.)
Last, run the old test_api.sh on a fresh database and a fresh server. It must still pass: a new rule must not break the old controls.
Check yourself
Why is the owner check inside the SQL query stronger than a check after it?
AND owner = ? never loads another user's row, so no later mistake can leak it. A check after the query must be remembered in every route.
Why does the rate limit come after the key check?
The limit is for each user, so the server must know the user first. The cost is that wrong keys are not limited; the Field notes cover this.
A new route is added. How does the test help?
Add lines that call it as the wrong user and with no key, and expect refusals. Run the suite before every deploy.
Field notes
- In production, put the server behind a reverse proxy that ends TLS. Plain HTTP sends the key in the clear (OWASP Top 10 "Cryptographic Failures").
- Limit failed authentication by address too, because key guessing is not limited here. Methods that the class does not name, such as
TRACE, still get the default Python error page: in production, put a proxy in front that answers them. - The controls of lessons 8 and 9 apply here too: a bearer or signed token must have its algorithm, signature and expiry checked, a browser front end needs an
Origincheck for cookie sessions and a CORS list, and a route must never run a shell with client text. - Send logs off the machine and alert on bursts of 401, 413 and 429 (OWASP Top 10 "Security Logging and Alerting Failures", the 2025 name; the 2021 edition says "Monitoring").