Cloud and DevOps
Security Basics for Backend Engineers
What an engineer who builds APIs has to get right: passwords, sessions, JWT, OAuth, authorisation, input handling, secrets and the crypto primitives behind them. Each bug is reproduced on a tiny local bank demo and then fixed, with output pasted from real runs (Python 3.9, PyJWT 2.15, argon2-cffi 25.1, cryptography 50).
Framing
Part 1 of 6 · the vocabulary and where to look
The words: AAA and CIA
Three questions are asked of every request.
| Term | Question | Typical mechanism | Failure status |
|---|---|---|---|
| Authentication | Who are you? | Password, session, token, mTLS | 401 |
| Authorisation | May you do this, to this object? | Roles, ownership checks, policies | 403 or 404 |
| Accounting | What did you do? | Audit log of security events | none, it is a record |
The CIA triad is what all of it protects: confidentiality (who can read), integrity (who can change), availability (can it be used).
Trap: authentication is not authorisation. Most real API breaches are a signed-in user reading something that is not theirs.
Trust boundaries and threat modelling
A trust boundary is any arrow where data moves between parties that trust each other differently. Validate and authorise on the receiving side of each one.
- 1 and 2: every byte from outside is attacker controlled, including headers such as
X-Forwarded-Forunless your proxy sets them. - 3: input will try to become SQL, so placeholders and a least-privilege database user.
- 4 and 5: outbound URLs may point inwards and anyone can POST to a webhook, so allow-list and verify signatures.
Threat modelling is four questions asked of that picture:
- What are we building? (the diagram)
- What can go wrong? (walk each arrow)
- What are we going to do about it?
- Did we do a good enough job?
Passwords and sessions
Part 2 of 6 · proving who the caller is, and remembering it
Storing passwords
Encryption can be reversed by whoever holds the key, so a stolen key means every password. A password hash is one-way, salted so equal passwords differ, and deliberately slow so guessing is expensive.
- The stored string carries its own algorithm, cost and salt, so one text column is enough and costs can be raised later.
mis memory in KiB,tpasses,pthreads. Tune until one hash takes roughly 50 to 250 ms on your server.- On login, if
check_needs_rehashis true, store a fresh hash while you still have the plain password.
Choice: argon2id first, bcrypt if the platform lacks it (bcrypt reads only the first 72 bytes). The time printed above is this laptop, not a target.
What never to do
| Never | Why | Instead |
|---|---|---|
| Store plain or encrypted passwords | One leak or one key exposes all of them | argon2id or bcrypt |
| MD5, SHA-1 or plain SHA-256 | Built to be fast: billions of guesses a second on a GPU | A slow, memory-hard hash |
| One global salt, or none | Equal passwords get equal hashes, tables can be precomputed | Random salt per password (the library does it) |
Compare secrets with == | Stops at the first different byte, which leaks timing | hmac.compare_digest(a, b) |
| Log or email a password | Logs outlive the database | Redact, send a reset link |
| "Unknown user" versus "wrong password" | Tells an attacker which accounts exist | One message for both |
Reset tokens
A reset link is a temporary password, so treat it like one: random, stored only as a hash, short-lived and single use.
- A fast SHA-256 is fine here because the token already has 256 random bits. Slow hashes are for low-entropy human passwords.
- Answer "if that address exists, we sent a link" either way, and end the user's other sessions after the reset.
Cookie session versus bearer token
A session keeps the state on the server and gives the browser an opaque id. A bearer token is sent by the client's own code, and may carry the state itself.
| Cookie session | Bearer token (JWT) | |
|---|---|---|
| Revoke | Delete the row, immediate | Wait for expiry, or keep a denylist |
| Per-request cost | One store lookup | One signature check |
| Main browser risk | CSRF | XSS reading the token |
| Fits | First-party web app | Mobile, service to service, many APIs |
Cookie flags and browser storage
| Flag | Effect | Stops |
|---|---|---|
HttpOnly | JavaScript cannot read the cookie | XSS stealing the session id |
Secure | Sent over HTTPS only | Sniffing on plain HTTP |
SameSite=Strict | Never sent on cross-site requests | CSRF, but also breaks arriving by link |
SameSite=Lax | Sent on top-level GET navigation only | CSRF on POST, PUT, DELETE |
SameSite=None | Sent everywhere, requires Secure | Nothing. Needed for real cross-site use. |
__Host- prefix | Requires Secure, Path=/, no Domain | A sibling subdomain overwriting it |
| Where a browser keeps a token | XSS can read it | Verdict |
|---|---|---|
HttpOnly cookie | No | Default choice. Add a CSRF defence. |
| JavaScript memory | Only while the page runs | Good for a short access token, refresh via cookie |
localStorage / sessionStorage | Yes, any script on the origin | Avoid for anything that grants access |
JWT and OAuth
Part 3 of 6 · signed tokens and delegated access
A JWT, field by field
A JWT is three base64url parts joined by dots: header.payload.signature. It is signed, not encrypted, so anyone can read it and only the key holder can change it.
isswho issued it,audwhich API it is for,subwho it is about: the verifier checks the first two and uses the third as the user id.iatandexpare Unix seconds.jtiis a unique id for denylists,scopeis checked per endpoint.
Asymmetric signing: ES256 and RS256
With HS256 every verifier holds the secret and could therefore mint tokens. With ES256 or RS256 only the auth service holds the private key, and APIs get a public key that can verify and nothing else.
kidnames the key, so the issuer can publish two keys (a JWKS document) and rotate without downtime.- The last line is the key-confusion attack failing: the verifier pins
algorithms, so a token cannot choose HS256 and use the public key as the secret. - RS256 works the same way with an RSA key. ES256 keys and signatures are much smaller.
The classic JWT mistakes
Each mistake is a check the verifier skipped. Here the verifier does all of them, and each bad token fails closed.
| Mistake | Result | Fix |
|---|---|---|
Trusting the token's own alg, including none | Unsigned or re-signed tokens accepted | Pass a fixed algorithms list |
Not checking exp | A stolen token works for ever | Require exp, leeway of seconds only |
Not checking aud and iss | A token for another API or from another issuer works here | Pass audience and issuer |
| Secrets or personal data in the payload | Readable by anyone who sees the token (last line above) | Ids and scopes only |
| No revocation plan | Logout and "account disabled" do nothing until expiry | Short access token, revocable refresh token, jti denylist |
| Short or shared HS256 secret | Brute-forced offline from one token | 32 random bytes or more, or asymmetric keys |
Clock skew: servers disagree by a second or two, so allow a leeway of about 30 seconds. More than that is just a longer token lifetime.
Access and refresh tokens, with rotation
The access token is short-lived and sent to APIs. The refresh token is long-lived, sent only to the auth service, stored server-side and replaced on every use.
Why revoke the family: the server cannot tell the thief from the owner, only that one token was used twice. Both lose access and the owner signs in again.
OAuth 2 roles, grants and scopes
OAuth 2 lets an app act on a user's data without ever seeing the user's password. This part is knowledge only: nothing here was run for this page.
| Grant | Who uses it | User present |
|---|---|---|
| Authorisation code with PKCE | Web, single-page and mobile apps | Yes |
| Client credentials | Service to service: the client is the resource owner | No |
| Refresh token | Any client renewing access | No |
| Implicit, password | Nobody: removed in OAuth 2.1 |
- A scope such as
accounts:readcaps what the token may do. It is not a substitute for checking who owns the object. - Client credentials: the service posts its id and secret (or a signed assertion) to the token endpoint and gets a short access token, with no refresh token.
Authorisation code with PKCE, and OIDC
The code travels through the browser, where it can be intercepted. PKCE binds it to a secret the client made up for this one login, so a stolen code is useless.
stateis random and checked on return: it is the CSRF defence for the redirect.- Redirect URIs are matched exactly against a registered list. A wildcard there hands codes to attackers.
- OpenID Connect adds the ID token (scope
openid): a JWT for the client app that says who signed in, withsub,nonceandauth_time. It also standardises discovery and the JWKS URL.
Trap: the access token is for the API, the ID token is for the client. Never accept an ID token as an API credential.
Authorisation and input handling
Part 4 of 6 · each bug reproduced on the demo, then fixed
RBAC, ABAC and deny by default
Authorisation and input handling
| RBAC | ABAC | |
|---|---|---|
| Decision from | The caller's roles | Attributes of caller, object and context |
| Example rule | teller may post deposits | Owner may transfer up to the daily limit, from a known device |
| Strength | Simple, easy to audit | Expresses ownership, tenancy, time, amount |
| Weakness | Role explosion, cannot say "own objects only" | Harder to test and to explain |
| In practice | Roles for which endpoints, attributes (ownership, tenant) for which objects | |
- Deny by default: a new endpoint with no rule must fail closed, not open.
- Hidden buttons and client-side checks are user experience. The server checks every time.
Broken object-level authorisation
Authorisation and input handling
The top API risk, also called IDOR: the caller is signed in, changes an id in the URL and gets someone else's object. The demo is a stdlib http.server bank where Rishikesh Agrawani (user 101) owns account 1 and Sandhya Agrawani (user 102) owns account 2.
- The fix is one condition, usually pushed into the query:
WHERE id = ? AND owner_id = ?. - 404 rather than 403 for other people's objects, so ids cannot be enumerated.
- Random ids (UUIDs) make guessing harder. They are not authorisation.
Mass assignment and unsafe deserialisation
Authorisation and input handling
Both bugs let the request body decide more than it should. Mass assignment copies every submitted field onto the record, including ones the user must never set.
Unsafe deserialisation is the same idea one level down (described, not exploited): pickle, marshal and yaml.load with an unsafe loader can run code while loading. For untrusted bytes use JSON, which can only produce dicts, lists, strings and numbers, then validate it.
Rule: an explicit input schema (pydantic, a dataclass, a Go struct with only the writable fields) fixes mass assignment and gives you validation in one step.
SQL and command injection
Authorisation and input handling
Injection is data being parsed as code. For SQL the fix is placeholders, shown with a working attack in the databases page; for the shell it is not using a shell.
- With a list there is no shell, so
;,|,$( )and backticks are ordinary characters. --ends option parsing, so input starting with-cannot become a flag.- Better still, use a library call (
os.stat, a zip module) and run no command at all.
Path traversal
Authorisation and input handling
A filename from the user joined to a folder can climb out of it with ../ or replace it with an absolute path.
Order matters: resolve first (which also follows symlinks), then check. Safer still, never take a filename: look the file up by a database id.
Server-side request forgery
Authorisation and input handling
If the server fetches a URL the user supplied, the user can aim it at things only the server can reach: cloud metadata, admin ports, internal services. The fix is an allow-list of hosts plus a check on the resolved address.
- Block-lists lose: decimal IPs, IPv6, redirects and
user@hosttricks all get round them. - Connect to the address you checked and refuse redirects, or DNS can change between check and fetch.
- Second layer: an egress firewall, so the API cannot reach the metadata address at all.
XSS and output encoding
Authorisation and input handling
Cross-site scripting is injection into HTML: text from one user runs as script in another user's browser, with that user's session.
- For a JSON API: send
Content-Type: application/jsonandX-Content-Type-Options: nosniff, and let the front-end framework escape. - Template engines with auto-escaping do this for you. The bugs are in the escape hatches:
|safe,innerHTML,dangerouslySetInnerHTML. - A Content-Security-Policy is the second layer, not the fix.
CSRF
Authorisation and input handling
Cross-site request forgery uses the fact that browsers attach cookies automatically: another site makes the victim's browser send a request that the API cannot tell from a real one.
| Fix | How it breaks the attack |
|---|---|
SameSite=Lax or Strict cookie | The cross-site POST arrives without the cookie |
| CSRF token | A random value tied to the session, sent in a header or form field. The evil site cannot read it. |
Check Origin | Reject state-changing requests whose origin is not yours |
| No state change on GET | Lax still sends cookies on top-level GET |
Interview point: an API authenticated only by an Authorization header is not exposed to CSRF, because the browser does not add that header by itself.
Secrets and cryptography
Part 5 of 6 · keeping keys out of sight, and what each primitive gives you
Secrets: where they leak, where they live
A one-line scan for the obvious patterns, run here on a scratch folder with two planted values:
- A dedicated scanner (gitleaks, trufflehog; not run for this page) also walks the full git history and belongs in CI and a pre-commit hook.
- Deleting the line does not remove it from history. A committed secret is leaked: rotate it.
| Environment variable | Mounted file | Secrets manager | |
|---|---|---|---|
| Visible to | The process, its children, /proc, crash dumps | Whoever can read the file | Identities allowed by policy |
| Rotation | Restart needed | File changes, app re-reads | Built in, versioned |
| Audit trail | None | None | Every read is logged |
| Typical leak | Debug page or log prints the environment | Wrong file mode, baked into an image | Over-broad access policy |
| Use when | Small deployments, non-critical config | Containers and orchestrators | Anything with a compliance or rotation need |
- Rotation: support two valid secrets at once (old and new), deploy the new one, then retire the old. If you cannot rotate without an outage, you cannot respond to a leak.
- Least privilege: one service account per service, with only the tables, buckets and queues it uses. The API's database user does not need
DROP.
In transit, at rest, end to end
TLS gives a confidential, tamper-evident channel to a server whose certificate proves its name: the handshake is in the networking page. It protects each hop, not the data once it lands.
Interview point: disk encryption only stops stolen disks and backups. A query through the running app, or a leaked database password, still reads everything.
Five primitives in one table
| Primitive | Keys | Gives you | Does not give | Examples |
|---|---|---|---|---|
| Hash | None | A fingerprint: integrity against accidents | Secrecy, or proof of who made it | SHA-256 |
| MAC | One shared secret | Integrity and authenticity between key holders | Secrecy, non-repudiation | HMAC-SHA256 |
| Signature | Private signs, public verifies | Integrity, authenticity, anyone can verify | Secrecy | Ed25519, ECDSA, RSA-PSS |
| Symmetric encryption | One shared secret | Secrecy, fast. With AEAD, integrity too. | A way to share the key | AES-GCM, ChaCha20-Poly1305 |
| Asymmetric encryption / key exchange | Public and private pair | Agreeing a key with a stranger | Speed: used only to set up symmetric keys | ECDH, RSA-OAEP |
Rule: never design your own scheme and never use a bare cipher mode. Pick a high-level recipe (TLS, AEAD, a password hasher) from a maintained library.
Verifying an HMAC-signed webhook
A webhook endpoint is public, so the sender signs the timestamp and raw body with a shared secret and the receiver recomputes it. The timestamp limits replay.
- Sign the raw bytes as received. Parsing and re-serialising JSON changes them.
- Inside the time window, store the event id and ignore duplicates: that makes the handler idempotent as well.
Authenticated encryption with AES-GCM
Authenticated encryption (AEAD) either returns the exact plaintext or raises: there is no "decrypted to garbage". Associated data is not encrypted but is bound to the ciphertext, which stops a value being copied to another row.
- Never reuse a nonce with the same key: for GCM that breaks both secrecy and integrity.
Fernetin the same library is the simpler recipe (it manages the nonce and adds a timestamp) when you do not need associated data.- Envelope encryption: a data key encrypts the row, a KMS key encrypts the data key, so rotating the master key does not rewrite the data.
Hardening and review
Part 6 of 6 · checklists, the OWASP lists and interview answers
Rate limits, lockout and headers
| Endpoint | Limit by | On breach |
|---|---|---|
| Login, reset, OTP | Account and IP, both | Growing delay, then 429 with Retry-After, alert |
| Expensive reads, exports, search | User or API key | 429, enforce page-size caps |
| Money-moving writes | User, plus business limits (daily amount) | Reject, step-up authentication |
| Everything | IP at the proxy | 429, see rate limiting in nginx |
Trap: a hard lockout after N failures lets an attacker lock any customer out. Prefer increasing delays, per-IP limits and MFA.
| Response header | Typical value | Purpose |
|---|---|---|
Strict-Transport-Security | max-age=31536000; includeSubDomains | Browser refuses plain HTTP next time |
Content-Security-Policy | default-src 'self' ('none' for a pure API) | Limits what an injected script can load or do |
X-Content-Type-Options | nosniff | JSON is never guessed to be HTML |
frame-ancestors in CSP, or X-Frame-Options | 'none' / DENY | No clickjacking through iframes |
Cache-Control | no-store on personal data | Shared caches and back buttons keep nothing |
CORS and the preflight
Browsers stop a script on one origin from reading responses from another. CORS is the server's way to relax that for named origins, and the preflight is the browser asking first.
| CORS is | CORS is not |
|---|---|
| A browser rule about reading cross-origin responses | Authentication or authorisation |
| Enforced by the browser, configured by the server | Applied to curl, servers or mobile apps |
| A relaxation of the same-origin policy | A CSRF defence: simple form POSTs skip the preflight |
- Allow an explicit list of origins. Reflecting whatever
Originarrives is the same as*. Access-Control-Allow-Credentials: truecannot be combined with*, and with a reflected origin it gives any site the user's session.
Errors, logs and dependencies
Tell the client as little as it needs and the log as much as an investigator needs, minus the secrets.
| Area | Do | Do not |
|---|---|---|
| Error bodies | Stable code, short message, request id | Stack traces, SQL, file paths, library versions |
| Security events to log | Login success and failure, denied access, password and role changes, token reuse | Passwords, tokens, full card numbers, session ids |
| Log fields | Who, what object, from where, when, outcome | Whole request bodies or header dumps |
| Dependencies | Pinned lock file, automated update PRs, an audit step in CI | Unpinned installs, base images never rebuilt |
Note: audit tools such as pip-audit and govulncheck were not run for this page.
OWASP Top 10 mapped to this page
Two lists, one for web applications (2021 numbering) and one for APIs (2023), covering mostly the same ground.
| Risk | Web 2021 | API 2023 | Chapter |
|---|---|---|---|
| Object-level access | A01 Broken Access Control | API1 BOLA | BOLA |
| Property-level access | A01 | API3 Broken Object Property Level Authorisation | Mass assignment |
| Function-level access | A01 | API5 Broken Function Level Authorisation | RBAC and deny by default |
| Authentication | A07 Identification and Authentication Failures | API2 Broken Authentication | Passwords, JWT mistakes |
| Cryptography | A02 Cryptographic Failures | Primitives, AEAD | |
| Injection, XSS | A03 Injection | Injection, XSS | |
| Design | A04 Insecure Design | API6 Unrestricted Access to Sensitive Business Flows | Threat modelling |
| Configuration | A05 Security Misconfiguration | API8 Security Misconfiguration | Headers, CORS |
| Resource use | API4 Unrestricted Resource Consumption | Rate limits | |
| Components | A06 Vulnerable and Outdated Components | API9 Improper Inventory Management | Dependencies |
| Integrity of code and data | A08 Software and Data Integrity Failures | API10 Unsafe Consumption of APIs | Deserialisation, Webhooks |
| Logging | A09 Security Logging and Monitoring Failures | Logs | |
| SSRF | A10 Server-Side Request Forgery | API7 Server Side Request Forgery | SSRF |
Check the date: OWASP revises these lists every few years and the numbering moves. Learn the risks, and look up the current order before an interview.
Interview questions
| Question | Short answer |
|---|---|
| Why hash passwords instead of encrypting them? | Nobody should be able to recover them, including us. Salted, slow, one-way: argon2id. |
| Sessions or JWT? | Sessions revoke instantly and suit first-party web. JWT avoids a lookup and suits many services, at the cost of revocation. |
| How do you revoke a JWT? | You mostly do not: keep it short, revoke the refresh token, keep a small jti denylist for emergencies. |
| HS256 or RS256/ES256? | Asymmetric when verifiers are separate services, so none of them can mint tokens. |
| What does PKCE protect? | The authorisation code: without the verifier a stolen code cannot be exchanged. |
| XSS versus CSRF? | XSS runs the attacker's script on your origin. CSRF sends the victim's cookies from another origin. |
| Does CORS protect my API? | No. It only decides which browser origins may read responses. |
| What is BOLA and how do you prevent it? | Reading another user's object by id. Check ownership in every handler, ideally in the query. |
| Where do secrets go? | A secrets manager or mounted files, short-lived where possible, never in git or images, rotated without downtime. |
| Encryption at rest is on. Are we done? | No. It covers stolen disks only: a query through the app or a leaked DB password still reads everything. |
Pre-release checklist
| Area | Check before shipping |
|---|---|
| Authentication | argon2id or bcrypt, same error for unknown user and wrong password, login rate limited, MFA available |
| Sessions and tokens | Cookies HttpOnly; Secure; SameSite. JWT verified with pinned algorithms, exp, aud, iss. Refresh tokens rotate. |
| Authorisation | Every endpoint has a rule, every object fetch checks owner or tenant, tests call each endpoint as the wrong user |
| Input | Schema with an allow-list of fields, SQL placeholders, no shell=True, no user-supplied paths or URLs without checks, no pickle |
| Output | Encoded for its context, correct Content-Type, nosniff, no stack traces |
| Secrets | None in the repo or image, scanner in CI, rotation rehearsed, service accounts least privilege |
| Transport and data | TLS everywhere including internal hops, HSTS, sensitive columns encrypted with AEAD, backups encrypted |
| Edge | Rate limits, body size limits, timeouts, CORS allow-list, security headers |
| Operations | Security events logged without secrets, alerts on spikes of 401, 403 and 429, dependencies audited |
Back to Cloud and DevOps.