Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Foundations / Web applications and APIs

Web applications and APIs cheat sheet

Call a server

TaskCommand
Show response headerscurl -si http://127.0.0.1:8300/
Show both directionscurl -sv http://127.0.0.1:8300/api/hello 2>&1 | grep -E '^[<>]'
Print only the statuscurl -s -o /dev/null -w '%{http_code} %{content_type}\n' http://127.0.0.1:8300/nothing
Save the addressH=http://127.0.0.1:8300
Create a notecurl -si -X POST $H/notes -H 'Content-Type: application/json' -d '{"text":"buy milk"}'
Delete a notecurl -s -w '[%{http_code}]\n' -X DELETE $H/notes/1
Accept only digits in an idre.fullmatch(r"/notes(?:/([0-9]{1,9}))?", self.path)
Refuse bad textif not isinstance(text, str) or not 1 <= len(text) <= 200

Read status codes

TermMeaning
201Created. 204 is deleted, no body
400Bad request. 415 is wrong content type
401Not authenticated
403Authenticated, but not allowed
404Not found, or not yours
405Method not allowed on this path
409Conflict with the current state, for example a quota
413Body too large
429Too Many Requests
502Bad gateway: a fetch to another server failed

Log in

TaskCommand
Make a keyexport API_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")
Compare a keyhmac.compare_digest(key.encode(), API_KEY.encode())
Hash a passwordhashlib.scrypt(password.encode(), salt=SALT, n=2**14, r=8, p=1) (demo cost; OWASP advises Argon2id, or scrypt with n=2**17)
Hash for an unknown user toohmac.compare_digest(hash_pw(password), USERS.get(user, DUMMY)), so the time is equal
Make a session idsecrets.token_urlsafe(32)
Set the cookief"sid={sid}; HttpOnly; SameSite=Strict; Path=/"
Log in, save cookiecurl -si -c jar.txt -X POST $H/login -d '{"user":"alice","password":"alice-pass"}'
Send the cookiecurl -s -b jar.txt $H/me
Send the keycurl -s -H "X-API-Key: $API_KEY" $H/api/data

Control access

TaskCommand
Test another user's notecurl -s -H "X-API-Key: $ALICE_KEY" $H/notes/2
Check owner in the queryWHERE id = ? AND owner = ?
Choose 404 or 403Use 404, so a missing note and a note that is not yours look the same
def find_note(user, note_id):
    note = NOTES.get(note_id)
    if note is not None and note["owner"] == user:
        return note
    return None

Stop injection

TaskCommand
Test a flawed queryx' OR 1=1 --
Parameterise a querydb.execute("SELECT text FROM notes WHERE owner = ? AND public = 1", (owner,))
Escape text for HTMLhtml.escape(note)
Sort by a column nameCheck the name against a fixed list. ? cannot hold a name

Stop unsafe fetches

TaskCommand
List allowed hostsALLOWED_HOSTS = {"127.0.0.1:8303"}
Check scheme and hostparts.scheme not in ("http", "https") or parts.netloc not in ALLOWED_HOSTS
Refuse redirectsopener = urllib.request.build_opener(NoRedirect)
Test a fetchercurl -s -G --data-urlencode "url=$u" $F

Limit, log and test

TaskCommand
Protect a .env filechmod 600 .env
Ignore it in Gitecho ".env" >> .gitignore
Limit requestsTokenBucket(rate=1, burst=3)
Cap the cost of a keyspent[key] = spent.get(key, 0) + 1 and refuse with 429 above DAILY_MAX
Refuse a bad lengthif not 0 <= size <= MAX_BODY: after int(...) in try, except ValueError: size = -1
Log without secretsself.log_message("%s %s %s", self.command, self.path.split("?")[0], code)
Rotate a keyWrite a new key to .env, restart, and expect 401 for the old key
Run the testsbash test_api.sh

Refuse in this order: key (401), rate (429), size (413, 400), route (404), input (415, 400), owner (404), method (405).

Close token and cross-site gaps

TaskCommand
Read a bearer tokenauth = self.headers.get("Authorization", ""), then auth[7:] after Bearer
Check a signed tokenheader["alg"] != "HS256", hmac.compare_digest(sig, sign(...)), claims["exp"] < time.time(); any error returns None
Send a bearer tokencurl -s -H "Authorization: Bearer $TOKEN" $H/me
Send CORS only to a listif origin in ORIGINS: then send Access-Control-Allow-Origin
Refuse a cross-site POSTif origin and origin not in ORIGINS: answer 403
Test that a text is absentcurl -si ... and case "$out" in *"$2"*) (the without function)

Close shell and field gaps

TaskCommand
Run a program with no shellsubprocess.run(["ls", "--", name], capture_output=True, text=True) after re.fullmatch(r"[a-z]{1,20}", name)
Pick the fields of an object{"owner": user, "text": text}, never note.update(body)
Send text in the query stringcurl -s -G --data-urlencode "dir=docs; echo pwned" $H/list

Shell helpers

TaskCommand
Remove a variableunset API_KEY
Read the exit code of the last commandecho $?
Pass on the arguments from the third"${@:3}"
Search a file for plain text, even a text that starts with -grep -qF -- "$KEY" server.log
Run a server in the background, then stop itpython3 notes_api.py 2> server.log &, then SERVER=$! and later kill $SERVER
List the ports in usess -ltn (Linux) or lsof -iTCP -sTCP:LISTEN -n -P (macOS)
Put the output of a command into a variableAPI_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")
Set a variable for one commandDAILY_MAX=3 python3 limits.py
Create an empty filetouch docs/a.txt
Read the value after = in a filecut -d= -f2 .env
Wait for some secondssleep 3
Count from 1 to Nseq 40
Make a file of N lettershead -c 2000 /dev/zero | tr '\0' a
Copy a file with one text changedsed 's/old/new/' in.py > out.py
Stop curl after some secondscurl -m 3 ...
Add 1 to a shell numbern=$((n+1))

Safety habits