Day 44 ยท Locks, badges and guest lists

Security, AuthN & AuthZ

You will be able to
  • Distinguish hashing from encryption and explain why passwords are hashed, never encrypted
  • Explain salted password hashing and why bcrypt/argon2 beat SHA-256 for passwords
  • Compare sessions and JWTs, including the JWT revocation pitfall
  • Walk through an OAuth2/OIDC authorization-code flow and name each actor
  • Apply least privilege and RBAC to an API design
Today's ~125 minutes
Spaced-rep warm-up: due flashcards (incl. Day 43 TLS)10 min
ELI5 + tech read: locks vs badges vs guest lists20 min
Guided: salted hashing + JWT by hand40 min
Practice: the auth design review20 min
Project: auth memo + password module25 min
Quiz + flashcards10 min

Builds on: Day 43 โ€” Networking & TLS ยท Day 41 โ€” HTTP & your first API ยท Day 38 โ€” Database internals โ€” where credentials live

The analogy

An office building runs three separate security systems, and mixing them up is how break-ins happen. The lock on the front door is encryption: anyone with the key can lock and unlock โ€” it is reversible by design. The visitor logbook is hashing: the guard writes a smudge-proof fingerprint of your ID into the book; nobody can reconstruct your ID from the fingerprint, but tomorrow they can check "same person?" by fingerprinting you again. The badge on your lanyard is authentication โ€” it proves who you are. The guest list on each meeting-room door is authorization โ€” being in the building (authenticated) does not mean every door opens for you.

Web security is these systems composed: TLS locks the trucks between buildings (Day 43), password hashes are the fingerprint logbook, sessions and JWTs are the badge, and role checks are the per-door guest list. Most real breaches are not lock-picking โ€” they are a badge that never expires, a guest list nobody prunes, or a logbook that stored the actual IDs instead of fingerprints.

Why this matters on the job

AI applications concentrate risk: they hold API keys worth real money per token, they proxy user data into third-party models, and agents can act with the permissions you give them. "Least privilege" stops being a slogan the day your demo agent has a database tool and a customer asks what stops it from reading other tenants' rows. Every enterprise deal you touch as an FDE begins with a security questionnaire โ€” SSO (OAuth2/OIDC), secrets handling, RBAC โ€” and engineers who can answer precisely close deals faster. On Day 132 prompt injection joins this threat model; today's foundations are what injection attacks try to bypass.

Watch it happen

Badges, not master keys โ€” the OAuth2 authorization-code flow

step 1 / 6
Youbrowserโ†’Appwants accessโ†’Auth serverlogin + consentโ†’Token swapback channelโ†’APIyour data
โœ‰ click: "Sign in with Google"

The problem: an app wants to read your calendar, but giving it your password would give it EVERYTHING, forever. OAuth2 issues a scoped, expiring badge instead. It starts with a click.

Guided practice

guided 1

Salted, slow password hashing โ€” and why fast is fatal

20 min
  1. Run part 1 of the starter: hash the same password twice with SHA-256. Identical outputs โ€” why is that a problem for a leaked database? (Same password โ†’ same hash โ†’ crack once, unlock everyone.)
  2. Part 2 salts each hash with random bytes. Confirm the same password now produces different digests, and that verification still works because the salt is stored alongside.
  3. Part 3 uses pbkdf2 with 600k iterations. Time one verification. Multiply: at this cost per guess, how long do 1 billion guesses take on this machine vs plain SHA-256?
  4. Write the two-line summary in your notes: salt defeats precomputation; work factor defeats brute force.
๐Ÿ python โ€” editable, runs in your browser
Ctrl/โŒ˜+Enter runs ยท Tab indents ยท numpy/pandas/sklearn auto-load on import (torch and network calls need a local run)
guided 2

Build and break a JWT by hand

20 min

JWTs are just base64url + a signature. Building one demystifies every pitfall.

  1. Run the starter: it mints a token with an HMAC-SHA256 signature, then verifies it.
  2. Decode the payload WITHOUT the key (part 2). Lesson one: anyone can read claims โ€” encoded is not encrypted.
  3. Tamper with the payload (change role to admin) and re-verify. The signature check fails โ€” that is the entire security model.
  4. Re-sign the tampered payload WITH the key and watch it verify. Lesson two: whoever holds the signing key mints identity; key management IS auth security.
  5. Check the exp claim logic: set exp in the past and confirm your verify function rejects it. Lesson three: expiry is the only built-in revocation.
๐Ÿ python โ€” editable, runs in your browser
Ctrl/โŒ˜+Enter runs ยท Tab indents ยท numpy/pandas/sklearn auto-load on import (torch and network calls need a local run)

On your own

The auth design review

20 min

A junior teammate proposes this for your Day 42 notes service: passwords stored as SHA-256 (no salt), a JWT with a 30-day expiry containing the user's email and plaintext API quota, admin checks done in the frontend ("we hide the delete button"), and the signing key committed in config.py "so tests pass."

Your goal: write a review with (1) every flaw found (there are at least five), (2) the concrete fix for each, (3) the one-line principle behind each fix (salting, short expiry, server-side authZ, secrets management, least privilege).

Hints: what happens on database leak? On stolen token? On a curl request that skips the frontend? On a public repo?

Ship before you stop

Auth decision memo + password module

Two deliverables in your practice repo. (1) auth_memo.md: for the notes service you will harden tomorrow, decide sessions vs JWT vs API keys for its two clients (a web UI and a CLI script), justify in a paragraph each, and draw the OAuth2 authorization-code flow as a numbered ASCII sequence with all four actors. (2) auth_lib.py + tests: hash_password, verify_password (salted pbkdf2, constant-time compare), and new_api_key (returns the key once, stores only its hash). Tomorrow (Day 45) this module gets wired into the real service โ€” write it like production code.

Rubric โ€” check what you completed (0/6)

Common mistakes & misconceptions

  • Encrypting passwords instead of hashing them. Encryption is reversible โ€” a stolen key un-scrambles every password. Hashing has no way back; leaks expose fingerprints, not credentials.
  • Using fast hashes (SHA-256/MD5) for passwords. They are built for speed; attackers get billions of guesses per second. Use bcrypt/argon2/pbkdf2 with a real work factor.
  • Treating a JWT as encrypted. The payload is base64url โ€” anyone can read it. The signature prevents tampering, not reading. Never put secrets in claims.
  • Long-lived JWTs "for convenience." A stolen 30-day token is a 30-day breach with no revocation. Short access tokens + refresh tokens is the standard shape.
  • Enforcing authorization in the client. Hiding the admin button stops nobody with curl. Every permission check must happen server-side, on every request.
  • Committing secrets to git "temporarily." Git history is forever; scanners find keys in minutes. Env vars or a secret manager from day one (Day 16 already gave you the config pattern).
Knowledge check

Q1. Why must password hashes be salted?

Q2. Your service must invalidate a specific user's access RIGHT NOW. Which design makes this trivially easy?

Q3. In the OAuth2 authorization-code flow, why does the app exchange the code for a token on its BACKEND rather than in the browser?

Go deeper โ€” curated resources

docsOWASP Top Ten โ€” web application risks โ†—25 mindocsOWASP Cheat Sheet Series โ€” Password Storage & Session Management โ†—20 mindocsFastAPI Security tutorial โ€” OAuth2 with JWT โ†—30 mindocsMDN: HTTP authentication โ†—15 min
If you have a third hour
  • The alg:none and key-confusion JWT attacks โ€” Historic libraries trusted the token's own alg header โ€” attackers set "none" or swapped RS256/HS256 to forge tokens. Rule: the server pins the algorithm, never the token.
Done means
  • Both guided labs run; tamper test demonstrably fails verification
  • Design review finds โ‰ฅ 5 flaws with fixes and principles
  • auth_lib.py committed with passing tests
  • OAuth2 flow drawn from memory with all four actors
  • Quiz โ‰ฅ 2/3
How this connects

โ† Back: TLS from Day 43 secures the wire; today secures identity and permission on top of it. The env-var config discipline from Day 16 is exactly where signing keys and secrets belong, and Day 38 told you where credential tables live.

Forward โ†’: Tomorrow (Day 45) you wire auth_lib into the real service. On Day 132 prompt injection attacks the NEW identity problem โ€” an LLM that can be talked into misusing its permissions โ€” and the least-privilege habit you built today is the main defense. Day 159 extends this into production compliance, and Day 169 covers enterprise SSO in the field.

Unlocks: D45 Web Service Architecture ยท D125 Agent Reliability ยท D159 Production Security & Compliance Basics ยท D169 Enterprise Integration