Learnings

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

Framing

Three questions are asked of every request.

TermQuestionTypical mechanismFailure status
AuthenticationWho are you?Password, session, token, mTLS401
AuthorisationMay you do this, to this object?Roles, ownership checks, policies403 or 404
AccountingWhat did you do?Audit log of security eventsnone, 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

Framing

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.

Five boundaries on an ordinary request path.
  • 1 and 2: every byte from outside is attacker controlled, including headers such as X-Forwarded-For unless 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:

  1. What are we building? (the diagram)
  2. What can go wrong? (walk each arrow)
  3. What are we going to do about it?
  4. Did we do a good enough job?

Passwords and sessions

Part 2 of 6 · proving who the caller is, and remembering it

Storing passwords

Passwords and sessions

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.
  • m is memory in KiB, t passes, p threads. Tune until one hash takes roughly 50 to 250 ms on your server.
  • On login, if check_needs_rehash is 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

Passwords and sessions

NeverWhyInstead
Store plain or encrypted passwordsOne leak or one key exposes all of themargon2id or bcrypt
MD5, SHA-1 or plain SHA-256Built to be fast: billions of guesses a second on a GPUA slow, memory-hard hash
One global salt, or noneEqual passwords get equal hashes, tables can be precomputedRandom salt per password (the library does it)
Compare secrets with ==Stops at the first different byte, which leaks timinghmac.compare_digest(a, b)
Log or email a passwordLogs outlive the databaseRedact, send a reset link
"Unknown user" versus "wrong password"Tells an attacker which accounts existOne message for both

Reset tokens

Passwords and sessions

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

Passwords and sessions

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: the browser attaches the cookie, the server looks it up.
Bearer token: the client attaches it, the API verifies it locally.
Cookie sessionBearer token (JWT)
RevokeDelete the row, immediateWait for expiry, or keep a denylist
Per-request costOne store lookupOne signature check
Main browser riskCSRFXSS reading the token
FitsFirst-party web appMobile, service to service, many APIs

JWT and OAuth

Part 3 of 6 · signed tokens and delegated access

A JWT, field by field

JWT and OAuth

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.

  • iss who issued it, aud which API it is for, sub who it is about: the verifier checks the first two and uses the third as the user id.
  • iat and exp are Unix seconds. jti is a unique id for denylists, scope is checked per endpoint.

Asymmetric signing: ES256 and RS256

JWT and OAuth

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.

  • kid names 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

JWT and OAuth

Each mistake is a check the verifier skipped. Here the verifier does all of them, and each bad token fails closed.

MistakeResultFix
Trusting the token's own alg, including noneUnsigned or re-signed tokens acceptedPass a fixed algorithms list
Not checking expA stolen token works for everRequire exp, leeway of seconds only
Not checking aud and issA token for another API or from another issuer works herePass audience and issuer
Secrets or personal data in the payloadReadable by anyone who sees the token (last line above)Ids and scopes only
No revocation planLogout and "account disabled" do nothing until expiryShort access token, revocable refresh token, jti denylist
Short or shared HS256 secretBrute-forced offline from one token32 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

JWT and OAuth

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.

Rotation turns a stolen refresh token into an alarm.

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

JWT and OAuth

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.

Four roles. The password only ever goes to the authorisation server.
GrantWho uses itUser present
Authorisation code with PKCEWeb, single-page and mobile appsYes
Client credentialsService to service: the client is the resource ownerNo
Refresh tokenAny client renewing accessNo
Implicit, passwordNobody: removed in OAuth 2.1
  • A scope such as accounts:read caps 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

JWT and OAuth

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.

The verifier never passes through the browser's address bar.
  • state is 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, with sub, nonce and auth_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

RBACABAC
Decision fromThe caller's rolesAttributes of caller, object and context
Example ruleteller may post depositsOwner may transfer up to the daily limit, from a known device
StrengthSimple, easy to auditExpresses ownership, tenancy, time, amount
WeaknessRole explosion, cannot say "own objects only"Harder to test and to explain
In practiceRoles for which endpoints, attributes (ownership, tenant) for which objects
Three checks on every request, on the server. Anything not explicitly allowed is denied.
  • 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@host tricks 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.

Store the text as it is. Encode at the moment of output, for that output's context.
  • For a JSON API: send Content-Type: application/json and X-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.

The attacker never sees the cookie. The browser sends it for them.
FixHow it breaks the attack
SameSite=Lax or Strict cookieThe cross-site POST arrives without the cookie
CSRF tokenA random value tied to the session, sent in a header or form field. The evil site cannot read it.
Check OriginReject state-changing requests whose origin is not yours
No state change on GETLax 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

Secrets and cryptography

Every one of these is copied, cached and kept longer than the secret should 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 variableMounted fileSecrets manager
Visible toThe process, its children, /proc, crash dumpsWhoever can read the fileIdentities allowed by policy
RotationRestart neededFile changes, app re-readsBuilt in, versioned
Audit trailNoneNoneEvery read is logged
Typical leakDebug page or log prints the environmentWrong file mode, baked into an imageOver-broad access policy
Use whenSmall deployments, non-critical configContainers and orchestratorsAnything 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

Secrets and cryptography

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.

In transit covers the arrows, at rest covers the disk. Every box still reads the data.
End to end: only the two ends hold keys.

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

Secrets and cryptography

PrimitiveKeysGives youDoes not giveExamples
HashNoneA fingerprint: integrity against accidentsSecrecy, or proof of who made itSHA-256
MACOne shared secretIntegrity and authenticity between key holdersSecrecy, non-repudiationHMAC-SHA256
SignaturePrivate signs, public verifiesIntegrity, authenticity, anyone can verifySecrecyEd25519, ECDSA, RSA-PSS
Symmetric encryptionOne shared secretSecrecy, fast. With AEAD, integrity too.A way to share the keyAES-GCM, ChaCha20-Poly1305
Asymmetric encryption / key exchangePublic and private pairAgreeing a key with a strangerSpeed: used only to set up symmetric keysECDH, 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

Secrets and cryptography

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

Secrets and cryptography

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.
  • Fernet in 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

Hardening and review

EndpointLimit byOn breach
Login, reset, OTPAccount and IP, bothGrowing delay, then 429 with Retry-After, alert
Expensive reads, exports, searchUser or API key429, enforce page-size caps
Money-moving writesUser, plus business limits (daily amount)Reject, step-up authentication
EverythingIP at the proxy429, 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 headerTypical valuePurpose
Strict-Transport-Securitymax-age=31536000; includeSubDomainsBrowser refuses plain HTTP next time
Content-Security-Policydefault-src 'self' ('none' for a pure API)Limits what an injected script can load or do
X-Content-Type-OptionsnosniffJSON is never guessed to be HTML
frame-ancestors in CSP, or X-Frame-Options'none' / DENYNo clickjacking through iframes
Cache-Controlno-store on personal dataShared caches and back buttons keep nothing

CORS and the preflight

Hardening and review

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.

No matching allow header, and the browser never sends the PUT.
CORS isCORS is not
A browser rule about reading cross-origin responsesAuthentication or authorisation
Enforced by the browser, configured by the serverApplied to curl, servers or mobile apps
A relaxation of the same-origin policyA CSRF defence: simple form POSTs skip the preflight
  • Allow an explicit list of origins. Reflecting whatever Origin arrives is the same as *.
  • Access-Control-Allow-Credentials: true cannot be combined with *, and with a reflected origin it gives any site the user's session.

Errors, logs and dependencies

Hardening and review

Tell the client as little as it needs and the log as much as an investigator needs, minus the secrets.

AreaDoDo not
Error bodiesStable code, short message, request idStack traces, SQL, file paths, library versions
Security events to logLogin success and failure, denied access, password and role changes, token reusePasswords, tokens, full card numbers, session ids
Log fieldsWho, what object, from where, when, outcomeWhole request bodies or header dumps
DependenciesPinned lock file, automated update PRs, an audit step in CIUnpinned 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

Hardening and review

Two lists, one for web applications (2021 numbering) and one for APIs (2023), covering mostly the same ground.

RiskWeb 2021API 2023Chapter
Object-level accessA01 Broken Access ControlAPI1 BOLABOLA
Property-level accessA01API3 Broken Object Property Level AuthorisationMass assignment
Function-level accessA01API5 Broken Function Level AuthorisationRBAC and deny by default
AuthenticationA07 Identification and Authentication FailuresAPI2 Broken AuthenticationPasswords, JWT mistakes
CryptographyA02 Cryptographic FailuresPrimitives, AEAD
Injection, XSSA03 InjectionInjection, XSS
DesignA04 Insecure DesignAPI6 Unrestricted Access to Sensitive Business FlowsThreat modelling
ConfigurationA05 Security MisconfigurationAPI8 Security MisconfigurationHeaders, CORS
Resource useAPI4 Unrestricted Resource ConsumptionRate limits
ComponentsA06 Vulnerable and Outdated ComponentsAPI9 Improper Inventory ManagementDependencies
Integrity of code and dataA08 Software and Data Integrity FailuresAPI10 Unsafe Consumption of APIsDeserialisation, Webhooks
LoggingA09 Security Logging and Monitoring FailuresLogs
SSRFA10 Server-Side Request ForgeryAPI7 Server Side Request ForgerySSRF

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

Hardening and review

QuestionShort 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

Hardening and review

AreaCheck before shipping
Authenticationargon2id or bcrypt, same error for unknown user and wrong password, login rate limited, MFA available
Sessions and tokensCookies HttpOnly; Secure; SameSite. JWT verified with pinned algorithms, exp, aud, iss. Refresh tokens rotate.
AuthorisationEvery endpoint has a rule, every object fetch checks owner or tenant, tests call each endpoint as the wrong user
InputSchema with an allow-list of fields, SQL placeholders, no shell=True, no user-supplied paths or URLs without checks, no pickle
OutputEncoded for its context, correct Content-Type, nosniff, no stack traces
SecretsNone in the repo or image, scanner in CI, rotation rehearsed, service accounts least privilege
Transport and dataTLS everywhere including internal hops, HSTS, sensitive columns encrypted with AEAD, backups encrypted
EdgeRate limits, body size limits, timeouts, CORS allow-list, security headers
OperationsSecurity events logged without secrets, alerts on spikes of 401, 403 and 429, dependencies audited

Back to Cloud and DevOps.