system-design/security.md

27. Security: TLS, OAuth, JWT, OWASP

Security in a system design interview = a tax that pays itself back manyfold. Senior engineers think about it from the start; juniors bolt it on.

~7 min read·updated 5/29/2026

27. Security: TLS, OAuth, JWT, OWASP

Security in a system design interview = a tax that pays itself back manyfold. Senior engineers think about it from the start; juniors bolt it on.

27.1 The threat model mindset

For any system, ask:

  • Who are the attackers? Anonymous internet, authenticated users, insiders, supply chain.
  • What are they after? Data theft, account takeover, fraud, disruption, reputation.
  • What's the cost of compromise? PII leak (regulatory), financial loss, downtime.

The right defenses depend on threat model. A blog needs less than a bank.

27.2 Defense in depth

No single control prevents everything. Layer:

  • Edge: WAF, DDoS protection, rate limit.
  • Network: VPC, security groups, mTLS internally.
  • Auth: identity, MFA, session management.
  • Authz: per-action permission checks.
  • Data: encryption at rest, encryption in transit, key management.
  • Audit: immutable logs of sensitive actions.
  • People: least privilege, key rotation, training.

27.3 Encryption in transit (TLS)

(See chapter 3.) Always TLS, even internally.

  • TLS 1.3 default.
  • Strong cipher suites only (drop RC4, 3DES, MD5, SHA1).
  • HSTS (Strict-Transport-Security) header forces HTTPS for future visits.
  • Certificate management: Let's Encrypt + cert-manager, or managed (ACM, Cloud KMS).

mTLS

Mutual TLS — both client and server present certs. Used in:

  • Service mesh (Istio, Linkerd) for zero-trust internal traffic.
  • Webhook callers proving identity.
  • Enterprise B2B integrations.

Certificate pinning

Mobile apps store the expected server cert hash; reject mismatch. Defeats MITM via rogue CAs. Trade-off: cert rotation requires app update.

27.4 Encryption at rest

Most cloud providers encrypt all storage by default (AWS EBS, GCP Persistent Disk). What matters:

  • Who manages keys? Provider (default), customer-managed (CMK in KMS), or customer-supplied (BYOK).
  • Application-level encryption for sensitive fields (e.g., SSN, payment data) on top of disk encryption. Crypto-shred capability.
  • Envelope encryption: data encrypted with a data key (DEK); DEK encrypted with a master key (KEK) in KMS. Only KMS has KEK.

KMS

Hardware-backed key management. AWS KMS, GCP KMS, HashiCorp Vault. Use it for:

  • Master keys for envelope encryption.
  • Signing keys for JWTs.
  • Service-to-service secrets.
  • TLS certs.

Never put secrets in source code, env files in repos, or container images.

27.5 Secrets management

  • Never commit secrets to git.
  • Vault, AWS Secrets Manager, GCP Secret Manager, K8s Secrets (with encryption at rest).
  • Inject at runtime; rotate periodically.
  • For local dev: .env (gitignored) + secret-fetching scripts.

Detection tools: git-secrets, gitleaks, Trufflehog. Pre-commit hooks block leaks.

If a secret leaks: rotate immediately, rebuild deployments, audit logs.

27.6 Authentication

Verifying who the user/service is.

Passwords

  • Hash with bcrypt, argon2id, or scrypt. Never plain SHA / MD5.
  • Configurable cost so you can ramp up over years (10-12 bcrypt rounds; argon2id default).
  • Salt per user (built into bcrypt/argon2).
  • Pepper (server-side secret added to hash) — extra defense against DB leaks.
  • Block common passwords (HaveIBeenPwned password list).
  • Rate-limit + lockout on failed attempts.

MFA

TOTP (Google Authenticator), SMS (weak — SIM swap), WebAuthn / passkeys (best — hardware-backed).

Require for high-value actions: settings change, withdrawal, admin login.

SSO / Federation

  • SAML: enterprise, XML-based, complex.
  • OAuth 2.0 + OIDC: modern, JSON, used by "Sign in with Google."

OAuth 2.0

Authorization framework. Three main flows:

  1. Authorization Code (with PKCE): web apps, mobile apps. Redirect to authorization server, exchange code for token.
  2. Client Credentials: server-to-server.
  3. Device Code: TVs, CLIs without browser.

Implicit and Resource Owner Password flows are deprecated.

OpenID Connect (OIDC)

Layer on OAuth that adds identity (id_token JWT). What "Sign in with X" actually uses.

27.7 Authorization

Verifying what the user can do.

Models

  • RBAC (Role-Based Access Control): user has roles; roles have permissions. Coarse but simple. Scales to ~100s of roles before unwieldy.
  • ABAC (Attribute-Based): policy uses attributes (user dept, resource owner, time of day). Flexible; complex.
  • ReBAC (Relationship-Based): "user is editor of doc"; based on graph relations. Used by Google Zanzibar (paper, 2019).

Zanzibar

Google's global authorization service. Models permissions as relations: (object, relation, user). E.g., (doc:42, viewer, user:alice).

Supports:

  • Group membership (group:eng#member).
  • Inheritance.
  • Cross-tenant.
  • Causal consistency via Spanner.

Open-source clones: SpiceDB, OpenFGA, Ory Keto.

Per-request authz

Every request must check: "is this user allowed to do this action on this resource?"

  • Don't trust client-side only.
  • Centralize in a policy engine (OPA, Cedar, Zanzibar-style) or library.

27.8 JWT (JSON Web Tokens)

Self-contained, signed token. Format: header.payload.signature base64url-encoded.

header: { "alg": "RS256", "typ": "JWT" } payload: { "sub": "user_42", "exp": 1730000000, "scope": "read write" } signature: HMACSHA256(header.payload, secret) or RSA(...)

Pros

  • Stateless: server validates signature, no DB lookup.
  • Cross-service: pass token; receiver validates.
  • Standardized claims (iss, sub, aud, exp, iat).

Cons / pitfalls

  • Can't revoke before expiry without a denylist (defeating statelessness).
  • Long-lived JWTs are dangerous (leaked = full access for hours).
  • Pattern: short-lived access token (~15 min) + long-lived refresh token (~30 days, server-side revocable).
  • Algorithm confusion: don't accept alg: none; pin specific algorithms.
  • Storage: in browser, localStorage is XSS-vulnerable; cookies are CSRF-vulnerable. Trade-offs apply. HTTP-only Secure SameSite=Lax cookies for session.

Public-key signing (RS256, EdDSA)

Issuer signs with private key; verifiers use public key. Lets many services validate without sharing secrets.

JWKS endpoint exposes public keys; JWTs include kid (key ID) for rotation.

27.9 OWASP Top 10 (2021)

Memorize these.

  1. Broken Access Control: missing/incorrect authz. Most common.
  2. Cryptographic Failures: missing TLS, bad crypto, leaked secrets.
  3. Injection: SQL injection, NoSQL injection, OS command injection. Use parameterized queries. Always.
  4. Insecure Design: missing threat modeling.
  5. Security Misconfiguration: default creds, open S3 buckets, debug pages in prod.
  6. Vulnerable Components: outdated libs with known CVEs. Use Dependabot/Renovate.
  7. Authentication Failures: weak passwords, no MFA, broken session.
  8. Software & Data Integrity: tampered build artifacts, supply chain attacks. Sign artifacts; verify checksums.
  9. Security Logging Failures: no audit trail.
  10. SSRF: server-side request forgery. App makes a request to user-controlled URL → attacker hits internal services. Validate / allowlist; block link-local IPs (169.254.*).

27.10 Common attacks and mitigations

XSS (Cross-Site Scripting)

Attacker injects JS into your app. Stolen session, defacement.

Mitigations:

  • Output encoding (escape < > & " ' / in HTML context).
  • Content Security Policy (CSP) header.
  • HTTP-only cookies (JS can't read).
  • Input validation.

CSRF (Cross-Site Request Forgery)

Authenticated user visits malicious page that triggers an action on your site.

Mitigations:

  • CSRF tokens (sync token in cookie + body).
  • SameSite cookies (Lax or Strict).
  • Custom request headers (CORS preflight).

SQL Injection

User input ends up in a query.

Mitigations:

  • Parameterized queries (always).
  • Never string-concatenate user input into SQL.
  • ORM helps but doesn't fully prevent (raw query loopholes exist).

SSRF

Attacker tricks server into requesting URLs (e.g., http://169.254.169.254/... to get cloud metadata).

Mitigations:

  • Allowlist destinations.
  • Block private IP ranges, link-local, localhost.
  • Use proxy with policy.

IDOR (Insecure Direct Object Reference)

/orders/123 works; attacker tries /orders/124 and sees someone else's data.

Mitigations:

  • Authz check on every request.
  • Use opaque IDs (UUIDs/ULIDs) so guessing fails.
  • Centralized authz layer.

Mass assignment

Form submits { "name": "X", "is_admin": true }; ORM updates all fields.

Mitigations:

  • Allowlist fields per endpoint.
  • Strict DTOs.

Open Redirect

/login?redirect=evil.com → after login redirect to attacker site. Phishing vector.

Mitigations:

  • Allowlist redirect destinations.

Race conditions / TOCTOU

Check vs use; attacker exploits the gap. Common in payments (double-spend).

Mitigations:

  • Atomic ops (DB transactions, optimistic locking).
  • Idempotency keys.

27.11 Audit logging

Every privileged action: who, what, when, from where.

  • Tamper-evident (append-only, hashed chain).
  • Stored separately from app DB.
  • Retained per regulatory requirements (often 1-7 years).

GDPR, HIPAA, SOC 2, PCI-DSS — audits will demand this.

27.12 Privacy: PII

  • Minimize collection: don't store what you don't need.
  • Pseudonymize / anonymize for analytics.
  • Right to erasure (GDPR): you must be able to delete a user's data, including from backups (hard).
  • Data residency: some jurisdictions require local storage.

Strategy: encrypt PII fields with per-user keys; "delete" = destroy the user's key (crypto-shredding).

27.13 Supply chain

  • Pin dependencies; review updates.
  • SBOM (Software Bill of Materials).
  • Signed container images.
  • Reproducible builds where possible.
  • Watch for typosquatting (urllib3 vs urllib-3).

27.14 Zero trust

"Never trust, always verify" — even traffic inside your network. Everything authenticates and authorizes per-request.

Google's BeyondCorp model: no VPN; every request from any device authenticated, authorized, encrypted, audited.

27.15 Compliance frameworks

You'll be asked about these in industry:

  • SOC 2: trust principles (security, availability, etc.).
  • PCI-DSS: payment card data.
  • HIPAA: healthcare in US.
  • GDPR: EU privacy.
  • CCPA: California privacy.
  • ISO 27001: information security management.

You don't need details for system design interviews; just know they exist and constrain design (e.g., "PII at rest in EU only").

27.16 Interview talking points

  • Always TLS, including internal.
  • mTLS / service mesh for zero-trust internal.
  • Auth = OAuth/OIDC; tokens = short-lived JWT + refresh token; sensitive ops require MFA.
  • Authz = per-request, centralized policy.
  • Encrypt sensitive fields at app level on top of disk encryption.
  • KMS for key management.
  • Audit log for compliance.
  • WAF + rate limit at edge.

Key takeaways

  • Defense in depth: edge, network, auth, authz, data, audit.
  • TLS 1.3 everywhere; mTLS internally.
  • Hash passwords with bcrypt/argon2; MFA for sensitive ops.
  • Short-lived JWT + refresh token > long-lived JWT.
  • Authz on every request; OWASP Top 10 covers common slip-ups.
  • Audit log + KMS + secret manager are non-negotiable.

// 1 view

main
UTF-8·typescript