Exercise: Harden the Coffee Club API
Harden Bean There Coffee Club's working Express API before it goes online, with helmet's headers, CORS for the club's own pages, a rate limit on sign-in, an allow-list of fields and a check that refuses operator objects, and let Supertest's tests check every job.
Journeyman · Node.js · Web Development · Updated
Bean There Coffee Club's API works: members sign in, read their own record and change their favorite roast. 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: helmet's security headers, CORS for the club's own web pages only, a rate limit on sign-in, an allow-list of the fields a member may change, and a check that refuses an operator object in place of an email or password. Tests check every job as you go.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-node-harden-the-coffee-club-api, also linked from the Exercise box beside the lesson. Clone it into your nodejs-course folder. In VS Code's terminal:
cd ~/nodejs-course
git clone https://github.com/ask-codey/exercise-node-harden-the-coffee-club-api.git
Git makes a folder, exercise-node-harden-the-coffee-club-api, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and install the packages:
npm install
Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder.
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 the placeholder after JWT_SECRET= with a long random secret. The README has the command that prints one. The tests don't need it, but npm start does.
The folder holds:
app.js: the Express app,export const app = express(), with its routes already working, for you to harden.data.js: the club's three roasts and three members, kept in memory. Passwords are stored only as bcrypt hashes; each member's test password is in the comment at the top.send-problem.js: the readysendProblem(res, status, detail), which sends every error in the course's one shape,{ status, title, detail }, from Error Handling and Consistent Error Responses.auth.js:signTokenand therequireUsermiddleware, which readsAuthorization: Bearer <token>and checks it with the secret inJWT_SECRET.server.js: checks thatJWT_SECRETis set, then starts the API athttp://localhost:3100..env.exampleand.gitignore: the settings the API needs, and the file that keeps your.envout of Git.coffee-club.http: the requests to try with REST Client,Originheaders and a preflight included.app.test.jsandrate-limit.test.js: the tests, which send requests to your app with Supertest. The rate limit has its own file, so its count of tries starts from zero. You don't need to change them.
What to do
app.js already answers every route. The comment at its top lists them, and the five jobs. Each error is given as its status and its detail: sendProblem(res, 400, "Email and password must be text.") answers {"status":400,"title":"Bad Request","detail":"Email and password must be text."}.
// Harden it before it goes online:
// 1. helmet: every answer carries helmet's security headers, and none says X-Powered-By.
// 2. CORS: only the club's web pages, https://www.beanthere.example and https://beanthere.example, may call the
// API from a browser. A page from any other origin gets no Access-Control-Allow-Origin header.
// 3. A rate limit on POST /auth/sign-in only: 5 tries per 15 minutes from one address, then
// 429, "Too many sign-in attempts. Try again in 15 minutes."
// 4. PATCH /members/me changes only name and favoriteRoast. Any other field in the body, such as role,
// cupsLeft or email, is ignored.
// 5. POST /auth/sign-in answers 400, "Email and password must be text.", when the email or the password isn't a
// string (an operator object such as { "$gt": "" }, say), before it looks for the member.
- Add helmet for every answer.
- Add CORS with an allow-list of the club's two origins. Both jobs go before the routes.
- Limit sign-in with a rate limiter on
POST /auth/sign-inalone, answering 429 with the message above as JSON. - Allow-list the fields
PATCH /members/memay change, instead of copying the whole body onto the member. - Refuse anything but text for the email and the password in sign-in, with a 400.
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:
npm test
No server needs to be running: the tests hand each request straight to app. At first all 10 tests fail. That's expected: each job you finish turns its tests green. A failing test's message says what came back, for example The answer still says X-Powered-By: Express. helmet takes it away.
To try the API yourself, start it with npm start (or npm run dev, which restarts it each time you save), open coffee-club.http, and click Send Request above each request. Stop it with Ctrl+C.
Hints
- Middleware runs in the order you add it. Security Headers and Rate Limits adds
helmet()withapp.usebefore the routes, and CORS: Which Web Pages May Call Your API does the same withcors. - An origin matches exactly.
https://beanthere.exampleandhttps://www.beanthere.exampleare two origins, so the allow-list names both. CORS: Which Web Pages May Call Your API showscorswith a list of origins. - A limiter for one route goes between its path and its handler. Security Headers and Rate Limits builds a sign-in limiter with
windowMs,limitand ahandlerthat answers withsendProblem. - Copy only the fields you name. The Attacks to Expect: Injection and Mass Assignment loops over an allow-list and copies a field only when the body has it.
Object.assignwith the whole body is the hole. typeoftells text from an object. Check both fields beforemembers.find, and answer once, thenreturn.
When you're done
Every test is green, and with npm start running, coffee-club.http's requests get these answers (each request, then its answer's status line, the headers that matter, and the body):
GET /roasts
HTTP/1.1 200 OK
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
OPTIONS /members/me, from Origin: https://www.beanthere.example, asking for PATCH
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://www.beanthere.example
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
PATCH /members/me, as Dana, with { "favoriteRoast": "Night Owl", "role": "admin", "cupsLeft": 999 }
HTTP/1.1 200 OK
{"id":1,"name":"Dana","email":"dana@beanthere.example","role":"member","favoriteRoast":"Night Owl","cupsLeft":4}
POST /auth/sign-in, with { "email": { "$gt": "" }, "password": "dana-test-password" }
HTTP/1.1 400 Bad Request
{"status":400,"title":"Bad Request","detail":"Email and password must be text."}
POST /auth/sign-in, a wrong password, once the 5 tries are used up
HTTP/1.1 429 Too Many Requests
{"status":429,"title":"Too Many Requests","detail":"Too many sign-in attempts. Try again in 15 minutes."}
The same GET /roasts from Origin: https://coffee-deals.example answers 200 with no Access-Control-Allow-Origin header at all, and from Origin: https://www.beanthere.example with Access-Control-Allow-Origin: https://www.beanthere.example.
Now look back at app.js. If the club let members change one more field, say phone, how many lines would change? And which of your five jobs would still protect the API if someone called it from a script instead of a browser?
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.
On GitHub, click +, then New repository. Name it (for example
exercise-node-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-node-harden-the-coffee-club-api.git git add . git commit -m "My solution" git push -u origin mainYour
.envstays behind:.gitignorekeeps it out ofgit add ..Paste your repo's address, such as
https://github.com/your-name/exercise-node-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
Every API you put online needs these same five jobs, and none of them changes what the API does for the people it's meant for: that's what hardening is, closing the doors only strangers would try.