Exercise: Harden the Coffee Club API
Harden Bean There Coffee Club's working FastAPI app before it goes online, with CORS for the club's two web pages, security headers from a middleware, a slowapi rate limit on sign-in, an update model that can't set role, and the JWT secret read from the environment, and let the tests check every job.
Journeyman · FastAPI · Web Development · Updated
Bean There Coffee Club's API works: members sign in, read their own record and change their favorite roast, and staff can list every member. Next week it goes online, where anyone can send it anything. You'll harden it the way this chapter did, one job at a time: CORS for the club's own web pages, security headers on every answer, a rate limit on sign-in, an update model that can't make anyone staff, and the secret that signs tokens moved out of the code. Tests check every job as you go.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-harden-the-coffee-club-api, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:
cd ~/python-course
git clone https://github.com/ask-codey/exercise-fastapi-harden-the-coffee-club-api.git
Git makes a folder, exercise-fastapi-harden-the-coffee-club-api, with the exercise code inside. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment. On Windows (PowerShell):
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
On a Mac (zsh):
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
The prompt starts with (.venv) once the virtual environment is on. The exercise's README says what each command does, and what to do if PowerShell won't run the second one.
Then make your own .env, as Keeping Secrets Out of Your Code does: copy .env.example to .env (Copy-Item .env.example .env in PowerShell, cp .env.example .env in zsh), and replace change-me with a real secret from python -c "import secrets; print(secrets.token_urlsafe(32))". The tests don't need it, but fastapi dev will once job 5 is done.
The folder holds:
main.py: the app, its routers and its error handlers. Jobs 1, 2 and 3 go here, and the comment at its top lists every route and every job.rate_limit.py: where the limiter goes (job 3).routers/auth.py,routers/members.pyandrouters/roasts.py: the routes, all working. The sign-in route gets its limit in job 3.models.py:MemberChanges, the body ofPATCH /members/me(job 4).auth.py: passwords with pwdlib, tokens with PyJWT, and the signed-in member. Job 5 goes here.database.py,club_data.pyandmigrations/: the SQLite database, every SQL statement and the tables, ready to use. The app adds three roasts and two members the first time it starts: Dana (dana@example.com, passwordcorrect-horse-staple) and Marcus, who is staff (marcus@example.com, passwordlatte-art-staple).tests/: the tests, which send requests to your app withTestClienton a throwaway database. You don't need to change them.requirements.txt,pytest.ini,.env.exampleand.gitignore: the packages at exact versions, where pytest finds things, the settings the API needs, and the files Git leaves out (.envamong them).
What to do
Every route already answers. The comment at the top of main.py lists the five jobs:
1. CORS: only the club's web pages, https://www.beanthere.example and https://beanthere.example, may call the API
from a browser, with GET, POST and PATCH, and the Authorization and Content-Type headers. A page from any other
origin gets no Access-Control-Allow-Origin header.
2. Security headers: every answer carries X-Content-Type-Options: nosniff, X-Frame-Options: DENY and
Referrer-Policy: no-referrer.
3. A rate limit on POST /auth/token only: 5 tries a minute from one address. The sixth answers 429 in the one error
shape, detail "Too many sign-in tries. Try again in a minute.", with the header Retry-After: 60.
4. (models.py) PATCH /members/me may change only name and favorite_roast. A body with any other field, such as role
or email, answers 422.
5. (auth.py) JWT_SECRET comes from the environment, and the app stops with a clear message when it isn't set.
- Add CORS with
CORSMiddlewareand an allow-list of the club's two origins. - Add a middleware that puts the three security headers on every answer.
- Limit sign-in: make
limiterinrate_limit.py, put it onapp.state, add a handler forRateLimitExceededthat answers withproblem(), and put the limit on the sign-in route. - Fix
MemberChanges: onlynameandfavorite_roast, and extra fields forbidden. - Write
read_secret(name)inauth.py, as its docstring says, and setJWT_SECRET = read_secret("JWT_SECRET").
Keep every route answering as it does now: the tests sign Dana in and change her record along the way.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
pytest
No server needs to be running, and your coffee_club.db and .env are never touched: each test makes a new database, and the tests bring their own secret. At first 11 of the 15 tests fail, and 4 pass: those check what already works, such as Dana signing in, and that no other site gets a CORS header. Each job you finish turns its tests green. A failing test's message says what came back, for example PATCH /members/me with {"favorite_roast": "Midnight Harbor", "role": "staff"} should answer 422, but it answered 200 with {..."role":"staff"}.
To try the API yourself, start it with fastapi dev main.py and open http://127.0.0.1:8000/docs. Click Authorize, sign in as Dana, and try PATCH /members/me. Stop the server with Ctrl+C.
Hints
- CORS: CORS: Which Web Pages May Call Your API adds
CORSMiddlewarewithapp.add_middleware. An origin matches exactly, sohttps://beanthere.exampleandhttps://www.beanthere.exampleare both on the list. - Headers: Rate Limits and Security Headers writes the middleware with
@app.middleware("http"),async defandawait call_next(request). - The limit: the same lesson makes
Limiter(key_func=get_remote_address), setsapp.state.limiter, and handlesRateLimitExceeded.@limiter.limit("5/minute")goes under@router.post("/token"), and the route needs arequest: Requestparameter, or the app won't start. - The model: The Attacks to Expect: Injection and Mass Assignment takes
roleout and addsmodel_config = ConfigDict(extra="forbid"). The one error shape's 422 handler names each extra field for you. - The secret: Keeping Secrets Out of Your Code reads it with
os.environ.getand raisesRuntimeErrorwhen it's missing or empty.load_dotenv()is already called at the top ofauth.py.
When you're done
Every test is green: pytest's last line says 15 passed. Then, with the server running, open the docs page, sign in as Dana and send PATCH /members/me with {"role": "staff"}: it answers 422, and GET /members still answers 403 for her. Rename your .env for a moment and start the app: it stops at once, with your sentence on the last line.
Now look back at the jobs. Which of them would still protect the club if someone called the API from a script instead of a browser, and which wouldn't?
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step. Your .env stays behind, because .gitignore lists it.
On GitHub, click +, then New repository. Name it (for example
exercise-fastapi-harden-the-coffee-club-api), choose Public, and click Create repository. Leave out the README: your folder already has one.In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:
git remote set-url origin https://github.com/your-name/exercise-fastapi-harden-the-coffee-club-api.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-fastapi-harden-the-coffee-club-api, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.
So what
CORS, security headers, a rate limit, an allow-list of fields and secrets kept out of the code are the checklist every API goes through before it faces the internet, and you've now worked through all of it on a real app with tests that prove each one.