Lesson 07 · 40 minutes
Keep secrets out of code and limit what a client can cost you
- Load keys from the environment and a .env file that version control ignores
- Rotate a key and prove that the old key stops working
- Add a rate limit, a body size limit, a daily budget and a log that holds no secrets
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
On Monday your cloud bill is ten times the normal one. A script loop, started with a key that someone pasted into a public repository, called your LLM endpoint all weekend. Your manager asks for three changes before Friday: no secrets in code, a limit on how fast, how large and how many requests a key may send in a day, and a key that you can replace in minutes. Your task is to build these controls on your own machine, prove each one with requests, and then tune the limits for a stricter service.
Recall
Lesson 3. In the default server log of lesson 3, what did you find that should never be in a log?
The API key. It was in the URL as a query parameter, and the default log line holds the whole request line. A key in a URL ends up in logs, in browser history and in the Referer header.
Lesson 2. The notes API reads whatever Content-Length says. Which risk does that create?
A client can send a huge body and make the server use all its memory, or send a wrong length and cause an error. A size limit before the read stops it. This lesson adds that limit.
The idea
Three habits protect you.
Keep secrets outside the code. The program reads a key from an environment variable, a named value that the system gives to a process. For local work a .env file holds the values, the file is listed in .gitignore so version control never stores it, and its permissions allow only you to read it.
Rotate keys. To rotate is to make a new key, switch the server to it and kill the old one. Practise it before the day when you must do it in a hurry.
Limit the client. A token bucket is a basic rate limit. The bucket holds up to burst tokens and gains rate tokens each second. Each request takes one token. An empty bucket means 429 Too Many Requests. Each key has its own bucket, so one client cannot use up the tokens of the others. A client may make a short burst, but not a steady flood. A size limit stops one huge request from using your memory.
Cap the cost. A rate limit lets a slow, steady client go on for ever: one request a second is allowed all weekend. A daily budget counts what each key has used and refuses the rest. A real service counts tokens or money; this lab counts requests.
- Client → Server: POST with a key and a big body
- Server: compare the key with the .env key
- Server: take one token from the bucket
- Server → Client: 429 when the bucket is empty
- Server: compare Content-Length with the limit
- Server → Client: 413 when the body is too large
- Server → Client: 429 when the daily budget is used
- Server → Log: method, path and status only
Worked example
1. Make a .env file and protect it
echo writes text to a file with >. unset removes a variable from your terminal; here it removes any API_KEY left from lesson 3, because a real environment variable would win over the file. chmod (change mode) sets the permissions of a file, and ls -l shows them.
cd ~/krlab/web-apis
unset API_KEY
echo "API_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")" > .env
chmod 600 .env
echo ".env" >> .gitignore
ls -l .env-rw------- 1 you you 52 Nov 21 08:40 .envrw- for the owner means read and write; --- twice means no rights for the group and for everyone else. Each triple is one digit: r is 4, w is 2, so rw- is 6 and --- is 0, which gives 600. "Links" is the number of names that the file has, normally 1 (Part 1 of the Linux course shows permissions in full). So only the owner can read and write. The file .gitignore tells Git to skip .env. The sign >> adds a line to the end of a file, so a .gitignore that you already have stays whole.
2. Write the server
Create limits.py. Read it in this order: load_env, TokenBucket, then do_POST from top to bottom. Seven names are new:
os.environ.setdefaultsets a variable only when it does not exist yet.os.environ.get(name, default)reads a variable, or gives the default.time.monotonic()is a clock that never goes back, which suits a timer.- The status
429 Too Many Requestsmeans "slow down", and413 Content Too Largemeans that the body is bigger than the server accepts. int(...)raisesValueErrorwhen its text is not a number, so the code catches that and treats it as a bad length.log_requestis a method that the server calls after every request to write the log line. Defining it again replaces the default line.__init__runs when you writeTokenBucket(...).self.rateis a value that the object keeps between calls.buckets.setdefault(key, new)returns the bucket ofkey, and storesnewfirst when the key has none.
The program has six controls: it loads .env, checks the key, takes a token, checks the size, counts the daily budget, and logs only the method, the path without its query, and the status.
limits.py
import hmac, json, os, time
from http.server import BaseHTTPRequestHandler, HTTPServer
def load_env(path=".env"):
if os.path.exists(path):
for line in open(path):
name, _, value = line.strip().partition("=")
if name and not name.startswith("#"):
os.environ.setdefault(name, value)
load_env()
API_KEY = os.environ["API_KEY"]
MAX_BODY = 1024
DAILY_MAX = int(os.environ.get("DAILY_MAX", "100")) # requests for each key and day
spent = {} # key -> requests used so far
class TokenBucket:
def __init__(self, rate, burst):
self.rate, self.burst = rate, burst # tokens per second, bucket size
self.tokens, self.last = burst, time.monotonic()
def allow(self):
now = time.monotonic()
self.tokens = min(self.burst, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
buckets = {} # key -> its own bucket
class Handler(BaseHTTPRequestHandler):
def reply(self, status, obj):
data = json.dumps(obj).encode()
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="-"): # method, path without query, status
self.log_message("%s %s %s", self.command, self.path.split("?")[0], code)
def do_POST(self):
key = self.headers.get("X-API-Key", "")
if not hmac.compare_digest(key.encode(), API_KEY.encode()):
return self.reply(401, {"error": "not authenticated"})
bucket = buckets.setdefault(key, TokenBucket(rate=1, burst=3))
if not bucket.allow():
return self.reply(429, {"error": "slow down"})
try:
size = int(self.headers.get("Content-Length") or 0)
except ValueError:
size = -1 # not a number: bad
if size < 0:
return self.reply(400, {"error": "bad Content-Length"})
if size > MAX_BODY:
return self.reply(413, {"error": "body too large"})
spent[key] = spent.get(key, 0) + 1
if spent[key] > DAILY_MAX:
return self.reply(429, {"error": "daily budget used"})
self.reply(200, {"received": len(self.rfile.read(size))})
HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()3. Hit the rate limit
Start python3 limits.py in one terminal. In another (type cd ~/krlab/web-apis first, or cut cannot find .env), read the key from the file (cut -d= -f2 keeps the part after the =) and send five quick requests. The bucket has three tokens.
H=http://127.0.0.1:8300
KEY=$(cut -d= -f2 .env)
for i in 1 2 3 4 5; do curl -s -w ' [%{http_code}]\n' -X POST -H "X-API-Key: $KEY" -d hi $H/echo; done{"received": 2} [200]
{"received": 2} [200]
{"received": 2} [200]
{"error": "slow down"} [429]
{"error": "slow down"} [429]4. Hit the size limit
Wait three seconds with sleep 3 for the bucket to refill. Then send 2,000 bytes with a secret-looking value in the query string. head -c 2000 /dev/zero | tr '\0' a makes a file of 2,000 letters a, and --data-binary @big.txt sends that file as the body.
sleep 3
head -c 2000 /dev/zero | tr '\0' a > big.txt
curl -s -w ' [%{http_code}]\n' -X POST -H "X-API-Key: $KEY" --data-binary @big.txt "$H/echo?token=abc"{"error": "body too large"} [413]5. Read the log
Stop the server and read its terminal. The query ?token=abc is gone, and so are the headers and the key.
127.0.0.1 - - [21/Nov/2026 08:40:25] POST /echo 200
127.0.0.1 - - [21/Nov/2026 08:40:25] POST /echo 429
127.0.0.1 - - [21/Nov/2026 08:40:28] POST /echo 413The log is shortened here: one line for each kind of answer, where the real log has one line for each request.
Compare this with lesson 3, where the default log printed the key.
6. Spend the daily budget
The variable in front of a command, DAILY_MAX=3 python3 limits.py, is set for that one command only. The 2> server.log sends the log lines of the server into a file, so that they do not mix with the answers (step 7 adds to the same file with 2>>). The & at the end runs the server in the background of this terminal. $! holds the process number of that background job, so SERVER=$! saves it and kill $SERVER stops it. The sleep 1 after each request gives the bucket time to refill, so the rate limit does not answer first.
DAILY_MAX=3 python3 limits.py 2> server.log &
SERVER=$!
sleep 1
for i in 1 2 3 4; do curl -s -w ' [%{http_code}]\n' -X POST -H "X-API-Key: $KEY" -d hi $H/echo; sleep 1; done
kill $SERVER{"received": 2} [200]
{"received": 2} [200]
{"received": 2} [200]
{"error": "daily budget used"} [429]The fourth request has a valid key and passes the rate limit, but the budget of the key is gone. A real service resets the count each day; this one resets when you restart it. If the server does not start, an old one may still use port 8300: stop it first (lesson 0 shows the command that lists the ports in use).
7. Rotate the key
Keep the old key, make a new one in .env, restart the server and try both.
OLD=$KEY
echo "API_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")" > .env
python3 limits.py 2>> server.log &
SERVER=$!
sleep 1
KEY=$(cut -d= -f2 .env)
curl -s -w ' [%{http_code}]\n' -X POST -H "X-API-Key: $OLD" -d hi $H/echo
curl -s -w ' [%{http_code}]\n' -X POST -H "X-API-Key: $KEY" -d hi $H/echo
kill $SERVER{"error": "not authenticated"} [401]
{"received": 2} [200]The old key is dead. In a real system you give the new key to the client first, then switch the server, then remove the old key.
8. The finished files
These are the two files as they stand after the steps above. The .env holds a fake key for practice only: steps 1 and 7 make a new random key in your own file. The lab files of the course hold both.
The finished file: .env
.env
API_KEY=kr-lab-fake-key-0123456789-abcdefghijklmnopThe finished file: .gitignore
.gitignore
.envYour turn
The manager wants a stricter service. Change your own limits.py. There are no steps here.
- Make the bucket hold a burst of 5 tokens and refill slowly (change
TokenBucket(rate=1, burst=3)in thesetdefaultline torate=0.1, burst=5). Make the body limit 100 bytes. - Restart the server. Send 8 POST requests with the body
hiand the right key, in oneforloop as in step 3, so that all 8 arrive within a few seconds. The slow refill makes the result the same on a slow machine. Count how many answers are 200 and how many are 429. - Wait 30 seconds, so that three tokens are back. Send a body of exactly 100 bytes, then a body of exactly 101 bytes.
- Stop the server. Rename
.envto.env.off, make sure thatAPI_KEYis not set in your terminal, start the server again and read its exit code withecho $?. Then rename the file back.
Last, compare the answers for 100 and 101 bytes. The limit is "more than 100 is refused", so the first one must have passed.
Check yourself
You deleted a file with a key from your Git repository. Is the key safe now?
No. Git keeps the old commits, and anyone with a clone can read them. Treat the key as leaked and rotate it. Then remove it from history if you must, but rotation is the real fix.
Why does the size check use Content-Length and run before the body is read?
Reading first would put the whole body in memory, which is what the limit must prevent. The header gives the size in advance. Lesson 10 shows the check together with the other controls.
Why limit requests for each key and not for the whole server?
One shared limit lets a single client use all of it and lock out the others. A bucket for each key, as in limits.py, limits the client that misbehaves and protects the rest.
Field notes
- The OWASP API Security Top 10 names the problem "Unrestricted Resource Consumption": no limit on requests, size, time or cost. For LLM calls, count tokens or money in the daily budget, and cap the tokens of each request.
- A
.envfile is a convenience for development. In production use the secret store of your platform, and give each service its own key with the least access it needs. - Run a secret scanner on every commit and on old history. A key that reaches a public repository is often abused within minutes.
- This bucket lives in one process. With several servers, keep the counters in a shared store, or limit at the gateway in front of them. Behind a proxy, take the client from the key and not from the connection address.
- OWASP Top 10 "Security Logging and Alerting Failures" (the 2025 name; the 2021 edition says "Monitoring") is the other side: log the 401s, 413s and 429s, and alert on a burst. Log what happened, never the secret that it used.