Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 06 · Resilience, Security & OperationsChapter 32 of 33
31.
Phase 06Read time ~27 minDifficulty advanced

System Design Security Fundamentals

In this chapter
  • 01Introduction
  • 02What Are We Protecting?
  • 03CIA Triad
  • 04Confidentiality
  • 05Integrity
  • 06Availability
  • 07Authentication vs Authorization
  • 08Authentication
  • 09Authorization
  • 10Identity
  • 11Principle of Least Privilege
  • 12Defense in Depth
  • 13Security Boundaries
  • 14Zero Trust
  • 15Password Security
  • 16Salt
  • 17Password Verification
  • 18Multi-Factor Authentication
  • 19Something you know
  • 20Something you have
  • 21Something you are
  • 22Sessions
  • 23Secure Cookies
  • 24Secure
  • 25HttpOnly
  • 26SameSite
  • 27Token-Based Authentication
  • 28JWT
  • 29JWT Is Signed, Not Necessarily Encrypted
  • 30JWT Verification
  • 31Access Tokens and Refresh Tokens
  • 32Token Revocation
  • 33OAuth 2.0
  • 34OpenID Connect
  • 35API Authentication
  • 36API Keys
  • 37Authorization Models
  • 38Role-Based Access Control
  • 39Attribute-Based Access Control
  • 40Relationship-Based Authorization
  • 41Resource-Level Authorization
  • 42Multi-Tenant Security
  • 43Input Validation
  • 44SQL Injection
  • 45NoSQL Injection
  • 46Cross-Site Scripting
  • 47Cross-Site Request Forgery
  • 48CORS
  • 49TLS / HTTPS
  • 50Encryption at Rest
  • 51Encryption in Transit
  • 52Key Management
  • 53Secrets Management
  • 54Secret Rotation
  • 55Rate Limiting
  • 56DDoS Protection
  • 57WAF
  • 58Network Segmentation
  • 59Security Groups and Firewalls
  • 60Service-to-Service Security
  • 61Mutual TLS
  • 62Threat Modeling
  • 63STRIDE
  • 64Security Logging
  • 65Audit Logs
  • 66Security Monitoring
  • 67Account Lockout and Brute Force Protection
  • 68Session Security
  • 69Secure File Uploads
  • 70SSRF
  • 71Path Traversal
  • 72Supply Chain Security
  • 73Container Security
  • 74Kubernetes Security
  • 75Blast Radius
  • 76Secure Architecture Example
  • 77Secure Request Flow
  • 78Authentication Architecture
  • 79Authentication vs Authorization Interview Trap
  • 80Security and Distributed Systems
  • 81Security Trade-Offs
  • 82Common Security Mistakes
  • 83Mistake 1
  • 84Mistake 2
  • 85Mistake 3
  • 86Mistake 4
  • 87Mistake 5
  • 88Mistake 6
  • 89Mistake 7
  • 90Mistake 8
  • 91Mistake 9
  • 92Mistake 10
  • 93Mistake 11
  • 94Mistake 12
  • 95Security Design Checklist
  • 96Identity
  • 97Authorization
  • 98Data
  • 99Network
  • 100Application
  • 101Operations
  • 102Security Design Process
  • 103Security Interview Questions
  • 104Beginner
  • 105What is authentication?
  • 106What is authorization?
  • 107What is the CIA triad?
  • 108What is least privilege?
  • 109Why should passwords be hashed?
  • 110Intermediate
  • 111JWT vs session?
  • 112What is OAuth?
  • 113What is OpenID Connect?
  • 114What is CSRF?
  • 115What is XSS?
  • 116Advanced
  • 117How would you secure a microservices architecture?
  • 118How would you secure a multi-tenant SaaS application?
  • 119How do you reduce blast radius?
  • 120How do you secure service-to-service communication?
  • 121How would you design authentication for millions of users?
  • 122Mini Project — Secure an E-Commerce API
  • 123Final Mental Model
  • 124Summary
  • 125Exercises
  • 126Exercise 1
  • 127Exercise 2
  • 128Exercise 3
  • 129Exercise 4
  • 130Exercise 5
  • 131Exercise 6
  • 132Next Chapter
  • 133Chapter 31 — Secure Distributed Systems
In this chapter (133 sections)
01Introduction02What Are We Protecting?03CIA Triad04Confidentiality05Integrity06Availability07Authentication vs Authorization08Authentication09Authorization10Identity11Principle of Least Privilege12Defense in Depth13Security Boundaries14Zero Trust15Password Security16Salt17Password Verification18Multi-Factor Authentication19Something you know20Something you have21Something you are22Sessions23Secure Cookies24Secure25HttpOnly26SameSite27Token-Based Authentication28JWT29JWT Is Signed, Not Necessarily Encrypted30JWT Verification31Access Tokens and Refresh Tokens32Token Revocation33OAuth 2.034OpenID Connect35API Authentication36API Keys37Authorization Models38Role-Based Access Control39Attribute-Based Access Control40Relationship-Based Authorization41Resource-Level Authorization42Multi-Tenant Security43Input Validation44SQL Injection45NoSQL Injection46Cross-Site Scripting47Cross-Site Request Forgery48CORS49TLS / HTTPS50Encryption at Rest51Encryption in Transit52Key Management53Secrets Management54Secret Rotation55Rate Limiting56DDoS Protection57WAF58Network Segmentation59Security Groups and Firewalls60Service-to-Service Security61Mutual TLS62Threat Modeling63STRIDE64Security Logging65Audit Logs66Security Monitoring67Account Lockout and Brute Force Protection68Session Security69Secure File Uploads70SSRF71Path Traversal72Supply Chain Security73Container Security74Kubernetes Security75Blast Radius76Secure Architecture Example77Secure Request Flow78Authentication Architecture79Authentication vs Authorization Interview Trap80Security and Distributed Systems81Security Trade-Offs82Common Security Mistakes83Mistake 184Mistake 285Mistake 386Mistake 487Mistake 588Mistake 689Mistake 790Mistake 891Mistake 992Mistake 1093Mistake 1194Mistake 1295Security Design Checklist96Identity97Authorization98Data99Network100Application101Operations102Security Design Process103Security Interview Questions104Beginner105What is authentication?106What is authorization?107What is the CIA triad?108What is least privilege?109Why should passwords be hashed?110Intermediate111JWT vs session?112What is OAuth?113What is OpenID Connect?114What is CSRF?115What is XSS?116Advanced117How would you secure a microservices architecture?118How would you secure a multi-tenant SaaS application?119How do you reduce blast radius?120How do you secure service-to-service communication?121How would you design authentication for millions of users?122Mini Project — Secure an E-Commerce API123Final Mental Model124Summary125Exercises126Exercise 1127Exercise 2128Exercise 3129Exercise 4130Exercise 5131Exercise 6132Next Chapter133Chapter 31 — Secure Distributed Systems

1. Introduction#

Security is not a feature that we add after designing a system.

Security is an architectural property.

A system can be:

  • fast
  • scalable
  • highly available
  • fault tolerant

and still be a failure if an attacker can:

  • access another user's data
  • steal credentials
  • modify payments
  • bypass authorization
  • read secrets
  • impersonate administrators
  • inject malicious input
  • exploit internal services

A secure system therefore considers security at every layer:

User
  |
  v
DNS / Edge
  |
  v
Load Balancer
  |
  v
API Gateway
  |
  v
Application
  |
  +---- Authentication
  |
  +---- Authorization
  |
  v
Database
  |
  v
Storage

Security must exist across all of these boundaries.


2. What Are We Protecting?#

Before designing security, identify assets.

Typical assets include:

  • user accounts
  • passwords
  • access tokens
  • payment information
  • personal information
  • business data
  • databases
  • source code
  • API keys
  • encryption keys
  • infrastructure
  • logs
  • backups

Security design starts with:

What are the assets, who can access them, and what happens if they are compromised?


3. CIA Triad#

A foundational security model is the CIA triad.

             Security
             /      \
            /        \
   Confidentiality   Integrity
            \        /
             \      /
          Availability

Confidentiality#

Only authorized users should access data.

Example:

User A
  X
  |
User B's private messages

Integrity#

Data should not be modified improperly.

Example:

Payment = ₹1,000

An attacker must not be able to change it to:

Payment = ₹1

Availability#

Authorized users should be able to use the system when needed.

Examples:

  • DDoS protection
  • redundancy
  • rate limiting
  • failover

Security therefore overlaps with the availability topics from previous chapters.


4. Authentication vs Authorization#

This is one of the most important distinctions.

Authentication#

Authentication asks:

Who are you?

Examples:

  • username/password
  • OTP
  • passkey
  • biometric authentication
  • access token

Authorization#

Authorization asks:

What are you allowed to do?

Example:

User
  |
  +---- Read own profile
  |
  +---- Edit own profile
  |
  X---- Delete another user's account

Authentication without authorization is dangerous.

A user may successfully log in but still not have permission to access every resource.


5. Identity#

Identity represents an entity interacting with the system.

Examples:

  • human user
  • administrator
  • service
  • background worker
  • external partner

A useful model is:

Identity
   |
   v
Authentication
   |
   v
Authorization
   |
   v
Resource

6. Principle of Least Privilege#

Give an identity only the permissions it needs.

Bad:

Application
   |
   v
Database Admin

Better:

Application
   |
   v
Limited DB User
   |
   +---- SELECT
   +---- INSERT
   +---- UPDATE

The application should not automatically have permissions such as:

DROP DATABASE
CREATE USER
ALTER SYSTEM

Least privilege reduces blast radius.


7. Defense in Depth#

Do not rely on a single security mechanism.

Example:

WAF
 |
TLS
 |
Authentication
 |
Authorization
 |
Input Validation
 |
Rate Limiting
 |
Database Permissions
 |
Encryption
 |
Monitoring

If one control fails, another control may still reduce the impact.

This is called:

Defense in depth.


8. Security Boundaries#

A security boundary is a point where trust changes.

Example:

Internet
   |
   | untrusted
   v
API Gateway
   |
   | authenticated
   v
Application
   |
   | restricted
   v
Database

Do not assume that an internal network automatically means trusted.

A compromised service inside the network may still attack another service.


9. Zero Trust#

A simplified zero-trust principle is:

Do not automatically trust a request simply because it comes from inside the network.

Instead:

Request
  |
  v
Authenticate
  |
  v
Authorize
  |
  v
Validate
  |
  v
Access Resource

This is especially important in:

  • microservices
  • cloud environments
  • distributed systems
  • multi-tenant platforms

10. Password Security#

Never store passwords as plain text.

Bad:

username: anubhav
password: MyPassword123

If the database is compromised, the password is immediately exposed.

Instead:

Password
   |
   v
Password Hash Function
   |
   v
Stored Hash

Modern password hashing should use algorithms designed specifically for password storage, such as:

  • Argon2
  • bcrypt
  • scrypt

A general-purpose fast hash such as SHA-256 is not by itself a suitable password-storage strategy.


11. Salt#

A salt is a unique random value used with password hashing.

Conceptually:

Password + Salt
       |
       v
Password Hash

Different users with the same password should not end up with identical stored hashes.

Example:

User A:
password + saltA -> hashA
 
User B:
password + saltB -> hashB

12. Password Verification#

The server should not decrypt a password.

Instead:

User enters password
        |
        v
Hash using stored salt/configuration
        |
        v
Compare with stored password hash
        |
     /     \
  match   mismatch
    |         |
 login       reject

Passwords are generally stored in a one-way password hashing representation.


13. Multi-Factor Authentication#

MFA requires more than one authentication factor.

Common categories include:

Something you know#

  • password
  • PIN

Something you have#

  • security key
  • authenticator device

Something you are#

  • biometric

Conceptually:

Password
   +
Second Factor
   |
   v
Authenticated

MFA significantly reduces the impact of stolen passwords.


14. Sessions#

After authentication, a web application needs to remember the authenticated state.

One common model is a server-side session.

Browser
   |
   | login
   v
Server
   |
   v
Session Store

The server creates:

session_id = abc123

The browser receives a cookie containing the session identifier.

Subsequent requests send the cookie.

Browser
   |
Cookie: session_id=abc123
   |
   v
Server
   |
   v
Session Store

15. Secure Cookies#

Authentication cookies should normally be protected using appropriate cookie attributes.

Important attributes include:

  • Secure
  • HttpOnly
  • SameSite

Secure#

Cookie should be sent over HTTPS.

HttpOnly#

JavaScript cannot directly access the cookie through normal browser APIs.

This can reduce the impact of some XSS-based token theft scenarios.

SameSite#

Controls cross-site cookie behavior and helps mitigate certain CSRF scenarios.


16. Token-Based Authentication#

Another model is token-based authentication.

Login
 |
 v
Authentication Server
 |
 v
Access Token
 |
 v
Client
 |
 v
API

The client sends the token with requests.

Common formats include JWT, although opaque tokens are also widely used.


17. JWT#

JWT stands for:

JSON Web Token

A JWT commonly contains:

Header.Payload.Signature

Conceptually:

Header
   +
Payload
   +
Signature

A payload may contain claims such as:

{
  "sub": "user123",
  "role": "user",
  "exp": 1790000000
}

The exact claims depend on the application.


18. JWT Is Signed, Not Necessarily Encrypted#

A common misconception:

"JWT hides the data."

A normal signed JWT is not automatically encrypted.

Its payload can generally be decoded by the client.

The signature provides integrity/authenticity properties when correctly validated.

Therefore do not place sensitive secrets inside an ordinary JWT payload.


19. JWT Verification#

A server receiving a JWT should verify appropriate properties such as:

  • signature
  • issuer
  • audience
  • expiration
  • not-before where applicable
  • algorithm expectations

Conceptually:

Request
   |
   v
Extract token
   |
   v
Verify signature
   |
   v
Validate claims
   |
   v
Authorize request

20. Access Tokens and Refresh Tokens#

A common architecture uses:

Short-lived Access Token
+
Longer-lived Refresh Token

Example:

Access token:
15 minutes
 
Refresh token:
days/weeks depending on risk and design

The access token is used frequently.

The refresh token is used to obtain a new access token.

Shorter access-token lifetime can reduce the window of impact if an access token is stolen.


21. Token Revocation#

JWTs can introduce a revocation challenge.

If a self-contained access token remains valid until expiration, simply deleting a server-side session does not necessarily invalidate it.

Strategies include:

  • short-lived access tokens
  • token revocation lists where appropriate
  • rotating refresh tokens
  • server-side sessions
  • authorization checks against server state for high-risk actions

The correct choice depends on the security and operational requirements.


22. OAuth 2.0#

OAuth 2.0 is an authorization framework.

It allows a client application to obtain delegated access to resources.

Example:

User
 |
 v
Client Application
 |
 v
Authorization Server
 |
 v
Access Token
 |
 v
Resource Server

A key idea is:

The client does not need the user's password to access the authorized resource.


23. OpenID Connect#

OpenID Connect (OIDC) adds an identity layer on top of OAuth 2.0.

OAuth primarily concerns delegated authorization.

OIDC provides standardized authentication information.

Simplified:

OAuth 2.0
   |
Authorization
 
OIDC
   |
Authentication / Identity

This distinction is important in system design interviews.


24. API Authentication#

APIs may authenticate clients using:

  • sessions
  • OAuth access tokens
  • JWTs
  • API keys
  • mutual TLS
  • signed requests

Choice depends on the client type and threat model.

For example:

Public browser app
-> session/OIDC/OAuth
 
Service-to-service
-> workload identity / OAuth / mTLS
 
Simple internal integration
-> API key may be possible, with strong controls

25. API Keys#

An API key is a credential identifying a client or application.

Example:

Authorization: Bearer <credential>

API keys should be:

  • kept secret
  • rotated
  • scoped
  • rate limited
  • monitored

Never commit production API keys to source control.


26. Authorization Models#

Several authorization models are common.

Role-Based Access Control#

RBAC:

User
 |
 +---- Role: ADMIN
          |
          +---- CREATE
          +---- READ
          +---- UPDATE
          +---- DELETE

Attribute-Based Access Control#

ABAC considers attributes.

Example:

user.department == "finance"
AND
resource.region == user.region

Then access may be allowed.


Relationship-Based Authorization#

Access depends on relationships.

Example:

User
 |
 +---- owns ----> Document

The owner may edit the document.

This model is useful in collaboration and social systems.


27. Resource-Level Authorization#

Always authorize access to the specific resource.

Bad:

GET /users/123/profile
 
Authentication:
valid
 
Therefore:
allow

This is insufficient.

The server must also ask:

Is this authenticated user allowed to access user 123?

Otherwise the application may have an insecure direct object reference style vulnerability.


28. Multi-Tenant Security#

In a multi-tenant SaaS system:

Tenant A
   |
   +---- Users
   +---- Orders
 
Tenant B
   |
   +---- Users
   +---- Orders

A major security requirement is preventing:

Tenant A
   X
   |
Tenant B data

Authorization must include tenant context.

Database isolation strategies may include:

  • separate databases
  • separate schemas
  • tenant IDs with strict authorization
  • row-level security where appropriate

29. Input Validation#

Never assume input is safe.

Validate:

  • type
  • length
  • range
  • format
  • allowed values
  • structure

Example:

age = "hello"

should not be accepted when the API requires an integer.

Validation should happen server-side even if the frontend validates the same field.


30. SQL Injection#

SQL injection occurs when untrusted input changes SQL semantics.

Dangerous pattern:

"SELECT * FROM users WHERE name = '" + input + "'"

Use parameterized queries instead.

Conceptually:

SQL template
    +
Parameters
    |
    v
Database

The database should treat user input as data rather than SQL syntax.


31. NoSQL Injection#

NoSQL systems can also be vulnerable when untrusted input is interpreted as query operators or expressions.

The same principle applies:

Treat external input as data, not executable query logic.

Use appropriate driver APIs, validation, allowlists, and query construction mechanisms.


32. Cross-Site Scripting#

XSS occurs when attacker-controlled content is executed in a victim's browser.

Conceptually:

Attacker input
      |
      v
Application
      |
      v
Browser
      |
      v
Malicious script executes

Defenses include:

  • output encoding
  • safe templating
  • input validation where appropriate
  • Content Security Policy
  • avoiding unsafe HTML injection
  • secure cookie configuration

33. Cross-Site Request Forgery#

CSRF abuses a victim's authenticated browser context to trigger unwanted actions.

Example:

Victim logged into bank
       |
       v
Malicious website
       |
       v
Forged request
       |
       v
Bank

Common defenses include:

  • SameSite cookies
  • CSRF tokens
  • origin checks
  • appropriate API authentication architecture

34. CORS#

CORS stands for:

Cross-Origin Resource Sharing

It controls which browser origins may access resources through browser cross-origin mechanisms.

Example:

https://app.example.com

may be allowed to call:

https://api.example.com

A common mistake is:

Access-Control-Allow-Origin: *

without considering whether the API exposes sensitive authenticated functionality.

CORS is a browser security mechanism; it is not a replacement for authentication or authorization.


35. TLS / HTTPS#

HTTP without encryption exposes traffic to network observers.

HTTPS uses TLS.

Conceptually:

Client
   |
   | encrypted connection
   v
Server

TLS provides important protections including:

  • confidentiality
  • integrity
  • server authentication

Modern production systems should use HTTPS for sensitive traffic and generally for web traffic overall.


36. Encryption at Rest#

Data stored on disks or storage systems should be protected appropriately.

Examples:

  • database storage encryption
  • object storage encryption
  • disk encryption
  • encrypted backups

Conceptually:

Plain Data
   |
Encryption
   |
   v
Ciphertext
   |
Storage

37. Encryption in Transit#

Data moving between components should be protected.

Example:

Client
  |
 TLS
  v
API
  |
 TLS
  v
Service
  |
 TLS
  v
Database

Internal traffic should not automatically be considered safe merely because it stays inside a private network.


38. Key Management#

Encryption is only as strong as key management.

Keys should be:

  • protected
  • rotated
  • access-controlled
  • auditable
  • backed up according to recovery requirements

Avoid embedding encryption keys directly into source code.

A dedicated key-management system or cloud KMS is commonly used.


39. Secrets Management#

Secrets include:

  • database passwords
  • API keys
  • OAuth client secrets
  • signing keys
  • certificates
  • encryption keys

Bad:

const API_KEY = "production-secret";

Better:

Application
   |
   v
Secret Manager
   |
   v
Runtime Secret

Secrets should not be committed to Git.


40. Secret Rotation#

A secret should not necessarily live forever.

A rotation model:

Secret A
   |
   v
Issue Secret B
   |
   v
Update consumers
   |
   v
Validate
   |
   v
Revoke Secret A

Rotation reduces the lifetime of compromised credentials.


41. Rate Limiting#

Rate limiting controls request volume.

Example:

100 requests / minute / user

It can help against:

  • brute-force attacks
  • API abuse
  • resource exhaustion
  • credential attacks

A distributed system may implement rate limiting using:

  • Redis
  • API gateway
  • edge infrastructure
  • token bucket
  • leaky bucket

42. DDoS Protection#

Distributed Denial of Service attacks attempt to overwhelm resources.

Possible layers of defense:

Internet
   |
   v
DDoS Protection
   |
   v
CDN / Edge
   |
   v
WAF
   |
   v
Load Balancer
   |
   v
Application

Security architecture should attempt to stop expensive traffic before it reaches expensive backend resources.


43. WAF#

WAF stands for:

Web Application Firewall

A WAF can inspect HTTP traffic and apply rules against common web attack patterns.

Conceptually:

Request
   |
   v
WAF
 / \
allow block

WAF is an additional security layer, not a replacement for secure application code.


44. Network Segmentation#

Separate systems according to trust and exposure.

Example:

Internet
   |
Public Subnet
   |
Load Balancer
   |
Private Application Network
   |
Private Database Network

The database should generally not be directly exposed to the public Internet.


45. Security Groups and Firewalls#

Network controls can restrict:

  • source
  • destination
  • port
  • protocol

Example:

Internet
   |
   X----> Database:5432

while allowing:

Application
   |
   +----> Database:5432

This limits attack paths.


46. Service-to-Service Security#

In microservices:

Service A
   |
   v
Service B

Do not assume Service A is trustworthy forever.

Possible controls include:

  • service identity
  • mTLS
  • authorization policies
  • network policies
  • short-lived credentials
  • audit logging

47. Mutual TLS#

mTLS means mutual TLS authentication.

Normal TLS:

Client -> verifies Server

mTLS:

Client <-> Server

Both sides authenticate using certificates.

This is useful for:

  • service-to-service communication
  • internal APIs
  • zero-trust environments

48. Threat Modeling#

Threat modeling asks:

How could this system be attacked?

A useful process:

1. Identify assets
2. Identify trust boundaries
3. Identify attackers
4. Identify attack paths
5. Identify vulnerabilities
6. Identify mitigations
7. Validate controls

49. STRIDE#

A common threat-modeling framework is STRIDE.

Letter Threat
S Spoofing
T Tampering
R Repudiation
I Information Disclosure
D Denial of Service
E Elevation of Privilege

Example:

Login API

Ask:

  • Can someone spoof a user?
  • Can requests be tampered with?
  • Can actions be audited?
  • Can sensitive data leak?
  • Can the API be overwhelmed?
  • Can a normal user become an administrator?

50. Security Logging#

Security-relevant actions should be observable.

Examples:

  • login success
  • login failure
  • password reset
  • permission changes
  • admin actions
  • API key creation
  • suspicious requests
  • unusual access patterns

Logs should avoid exposing sensitive secrets.

Bad:

password=secret123

Better:

user_login_failed
user_id=123
reason=invalid_credentials

51. Audit Logs#

An audit log records important security or business actions.

Example:

2026-10-01
user=123
action=DELETE_ACCOUNT
resource=456
result=DENIED

Audit logs are useful for:

  • investigations
  • compliance
  • debugging
  • accountability

They should be protected against unauthorized modification.


52. Security Monitoring#

Security monitoring can detect patterns such as:

100 failed logins
        |
        v
Possible brute force

or:

Normal API usage
        |
        v
Sudden massive export
        |
        v
Potential account compromise

Monitoring should combine technical and business signals.


53. Account Lockout and Brute Force Protection#

Authentication endpoints are high-value targets.

Controls can include:

  • rate limiting
  • progressive delays
  • MFA
  • suspicious-login detection
  • credential stuffing protection
  • carefully designed account lockout

A naive permanent lockout can itself be abused to deny legitimate users access.


54. Session Security#

Session identifiers should be:

  • unpredictable
  • protected
  • short-lived where appropriate
  • invalidated when necessary

Important events may trigger session invalidation:

  • logout
  • password change
  • account compromise
  • administrator security action

55. Secure File Uploads#

File uploads create several risks.

Potential problems:

  • malicious files
  • oversized files
  • path traversal
  • executable content
  • content-type spoofing
  • malware

A secure upload architecture may be:

Client
  |
  v
Upload Service
  |
  v
Object Storage
  |
  v
Malware / Content Scan
  |
  v
Approved Storage

Do not blindly trust a filename or MIME type supplied by the client.


56. SSRF#

SSRF stands for:

Server-Side Request Forgery

It occurs when an attacker can influence the server to make unintended outbound requests.

Example:

Attacker
   |
   v
Application
   |
   v
Internal Service

Possible defenses:

  • URL allowlists
  • network restrictions
  • metadata-service protections
  • outbound filtering
  • strict URL parsing

57. Path Traversal#

Path traversal attempts to access files outside the intended directory.

Example concept:

/download?file=../../secret.txt

Defenses include:

  • safe path resolution
  • allowlists
  • rejecting unsafe path components
  • avoiding direct filesystem access from user-controlled paths

58. Supply Chain Security#

Applications depend on:

  • libraries
  • packages
  • containers
  • build tools
  • CI/CD systems

A compromised dependency can become a production security issue.

Important controls include:

  • dependency scanning
  • lockfiles
  • trusted registries
  • image scanning
  • SBOMs
  • signed artifacts
  • least-privilege CI/CD credentials

59. Container Security#

For containerized applications:

Source
  |
  v
Build
  |
  v
Container Image
  |
  v
Registry
  |
  v
Production

Security should consider:

  • minimal base images
  • non-root execution
  • image scanning
  • signed images
  • secret handling
  • runtime restrictions
  • network policies

60. Kubernetes Security#

Kubernetes security includes:

  • RBAC
  • namespaces
  • service accounts
  • network policies
  • pod security controls
  • secret management
  • admission controls
  • image policies

A dangerous pattern is giving workloads excessive permissions.

For example:

Application Pod
      |
      v
Cluster Administrator

A compromised application could then have an enormous blast radius.


61. Blast Radius#

Blast radius describes how much damage can occur after one component is compromised.

Bad:

One compromised service
        |
        v
Entire database
        |
        v
Entire platform

Better:

Compromised Service
        |
        v
Limited permissions
        |
        v
Small affected scope

Least privilege, segmentation, and separate credentials reduce blast radius.


62. Secure Architecture Example#

Consider an e-commerce system.

                    Internet
                       |
                       v
                 DDoS Protection
                       |
                       v
                      CDN
                       |
                       v
                      WAF
                       |
                       v
                Load Balancer
                       |
                       v
                  API Gateway
                       |
            +----------+----------+
            |                     |
            v                     v
        User Service        Order Service
            |                     |
            +----------+----------+
                       |
                       v
                Authorization
                       |
             +---------+---------+
             |                   |
             v                   v
         Database           Message Queue
             |
             v
       Encrypted Storage

Security layers include:

  • edge protection
  • TLS
  • authentication
  • authorization
  • network isolation
  • database permissions
  • secrets management
  • encryption
  • audit logging
  • rate limiting

63. Secure Request Flow#

A request can pass through multiple controls:

Client
  |
  v
TLS
  |
  v
DDoS Protection
  |
  v
WAF
  |
  v
Rate Limiter
  |
  v
Authentication
  |
  v
Authorization
  |
  v
Input Validation
  |
  v
Business Logic
  |
  v
Database Authorization
  |
  v
Audit Log

This is defense in depth.


64. Authentication Architecture#

A typical modern architecture:

                +--------------------+
                | Identity Provider  |
                +---------+----------+
                          |
                     Authenticate
                          |
                          v
Client ----------------> API
                          |
                     Access Token
                          |
                          v
                     Authorization
                          |
                          v
                       Resource

The identity provider can centralize authentication while applications enforce authorization.


65. Authentication vs Authorization Interview Trap#

Question:

"The user has a valid JWT. Should we allow the request?"

Answer:

Not necessarily.

The JWT may prove identity or carry claims, but the server must still determine whether the user has permission for the specific operation and resource.

Correct flow:

Authentication
      |
      v
Identity
      |
      v
Authorization
      |
      v
Resource Access

66. Security and Distributed Systems#

Security becomes more complicated as the number of components increases.

Monolith:

Client
  |
  v
Application
  |
  v
DB

Microservices:

Client
 |
API Gateway
 |
 +---- Service A
 |
 +---- Service B
 |
 +---- Service C
 |
 +---- Service D

Now there are many:

  • identities
  • network paths
  • credentials
  • trust boundaries
  • APIs
  • logs
  • secrets

Therefore security must be designed as a system-wide architecture.


67. Security Trade-Offs#

Security controls can affect:

  • latency
  • availability
  • developer experience
  • operational complexity
  • cost

Example:

mTLS

may improve service identity security but introduce certificate management complexity.

Another example:

Very short token lifetime

may reduce token exposure but increase refresh operations.

System design requires balancing security with operational requirements.


68. Common Security Mistakes#

Mistake 1#

Authentication without authorization.

Mistake 2#

Storing passwords in plaintext.

Mistake 3#

Putting secrets in Git.

Mistake 4#

Trusting internal network traffic automatically.

Mistake 5#

Using administrator credentials from applications.

Mistake 6#

Returning sensitive information in logs.

Mistake 7#

Relying only on a WAF.

Mistake 8#

No rate limiting on authentication endpoints.

Mistake 9#

Ignoring tenant isolation.

Mistake 10#

No audit trail for privileged operations.

Mistake 11#

Assuming JWT payloads are encrypted.

Mistake 12#

Using * CORS configuration without understanding the security implications.


69. Security Design Checklist#

Identity#

  • Authentication mechanism defined
  • MFA considered
  • Session/token strategy defined
  • Token expiration defined

Authorization#

  • RBAC/ABAC/relationship model defined
  • Resource-level authorization implemented
  • Tenant isolation enforced
  • Least privilege applied

Data#

  • Encryption at rest
  • Encryption in transit
  • Key management
  • Backup security

Network#

  • Public/private boundaries
  • Firewall controls
  • Network segmentation
  • Service identity

Application#

  • Input validation
  • SQL/NoSQL injection protection
  • XSS protection
  • CSRF protection where applicable
  • Secure file uploads
  • SSRF protection

Operations#

  • Secrets management
  • Secret rotation
  • Security logging
  • Audit logging
  • Monitoring
  • Incident response

70. Security Design Process#

When designing a system, use this sequence:

1. Identify assets
       |
       v
2. Identify users and services
       |
       v
3. Identify trust boundaries
       |
       v
4. Identify threats
       |
       v
5. Design authentication
       |
       v
6. Design authorization
       |
       v
7. Protect data
       |
       v
8. Protect network
       |
       v
9. Reduce blast radius
       |
       v
10. Add monitoring/auditing
       |
       v
11. Test security controls

71. Security Interview Questions#

Beginner#

1. What is authentication?#

Authentication verifies identity.

2. What is authorization?#

Authorization determines what an authenticated identity is allowed to do.

3. What is the CIA triad?#

Confidentiality, Integrity, Availability.

4. What is least privilege?#

Granting only the permissions required to perform a task.

5. Why should passwords be hashed?#

To avoid storing recoverable plaintext passwords and reduce the impact of database compromise.


Intermediate#

6. JWT vs session?#

Sessions commonly store server-side state identified by a session cookie. JWT-based authentication can carry signed claims in the token and may reduce server-side session lookup, but introduces token lifecycle and revocation considerations.

7. What is OAuth?#

An authorization framework for delegated access.

8. What is OpenID Connect?#

An identity/authentication layer built on OAuth 2.0.

9. What is CSRF?#

An attack where a victim's authenticated browser context is abused to perform an unwanted action.

10. What is XSS?#

Injection of attacker-controlled script/content into a context where it executes in a victim's browser.


Advanced#

11. How would you secure a microservices architecture?#

Discuss:

  • service identity
  • authentication
  • authorization
  • mTLS where appropriate
  • network policies
  • least privilege
  • secrets management
  • API gateway
  • rate limiting
  • audit logs
  • centralized security monitoring

12. How would you secure a multi-tenant SaaS application?#

Discuss:

  • tenant-aware authorization
  • tenant isolation
  • database isolation strategy
  • resource-level checks
  • encryption
  • audit logging
  • prevention of cross-tenant access

13. How do you reduce blast radius?#

Use:

  • least privilege
  • segmentation
  • separate credentials
  • isolated services
  • limited IAM permissions
  • network policies
  • scoped tokens

14. How do you secure service-to-service communication?#

Possible mechanisms:

  • mTLS
  • OAuth/workload identity
  • short-lived credentials
  • network restrictions
  • authorization policies
  • audit logging

15. How would you design authentication for millions of users?#

Discuss:

Global edge
   |
Load balancing
   |
Authentication service
   |
Identity store
   |
Token/session infrastructure

Then consider:

  • password hashing
  • MFA
  • rate limiting
  • token lifecycle
  • session management
  • database scaling
  • caching
  • abuse detection
  • availability
  • recovery

72. Mini Project — Secure an E-Commerce API#

Design security for:

POST /orders
GET /orders/:id
POST /payments
GET /users/:id

Requirements:

  • users can see their own orders
  • administrators can manage orders
  • users cannot access another user's data
  • payment operations require strong authorization
  • APIs must resist abuse

Design:

Client
  |
  v
TLS
  |
  v
WAF
  |
  v
Rate Limiter
  |
  v
API Gateway
  |
  v
Authentication
  |
  v
Authorization
  |
  v
Application
  |
  v
Database

Answer:

  1. How are users authenticated?
  2. How are roles represented?
  3. How do you enforce resource ownership?
  4. How do you protect payment APIs?
  5. How do you prevent SQL injection?
  6. How do you protect secrets?
  7. How do you audit admin actions?
  8. How do you rate-limit login?
  9. How do you protect internal services?
  10. What happens if one service is compromised?

73. Final Mental Model#

Think about security as multiple questions.

WHO ARE YOU?
     |
     v
Authentication
     |
     v
WHAT CAN YOU DO?
     |
     v
Authorization
     |
     v
WHAT DATA CAN YOU ACCESS?
     |
     v
Resource / Tenant Isolation
     |
     v
HOW IS DATA PROTECTED?
     |
     v
Encryption
     |
     v
HOW DO WE LIMIT DAMAGE?
     |
     v
Least Privilege + Segmentation
     |
     v
HOW DO WE DETECT ATTACKS?
     |
     v
Logging + Monitoring
     |
     v
HOW DO WE RECOVER?
     |
     v
Incident Response + DR

This connects security with the previous chapters on availability, fault tolerance, and disaster recovery.


74. Summary#

In this chapter we learned:

  • CIA triad
  • assets and security boundaries
  • authentication
  • authorization
  • identity
  • least privilege
  • defense in depth
  • zero trust
  • password hashing
  • salts
  • MFA
  • sessions
  • secure cookies
  • token authentication
  • JWT
  • access and refresh tokens
  • OAuth 2.0
  • OpenID Connect
  • API keys
  • RBAC
  • ABAC
  • relationship-based authorization
  • resource-level authorization
  • multi-tenant security
  • input validation
  • SQL injection
  • NoSQL injection
  • XSS
  • CSRF
  • CORS
  • TLS/HTTPS
  • encryption at rest
  • encryption in transit
  • key management
  • secrets management
  • secret rotation
  • rate limiting
  • DDoS protection
  • WAF
  • network segmentation
  • firewalls
  • service-to-service security
  • mTLS
  • threat modeling
  • STRIDE
  • security logging
  • audit logs
  • brute-force protection
  • secure file uploads
  • SSRF
  • path traversal
  • supply-chain security
  • container security
  • Kubernetes security
  • blast-radius reduction
  • secure distributed architecture
  • security trade-offs
  • security interview questions

The central principle is:

Security is not one component. It is a layered system of identity, authorization, isolation, encryption, validation, monitoring, and recovery.


75. Exercises#

Exercise 1#

Explain:

Authentication
Authorization
Accounting/Auditing

and give one example of each.

Exercise 2#

Design authentication for a consumer application with 50 million users.

Exercise 3#

Design authorization for a multi-tenant SaaS platform.

Exercise 4#

Explain how an attacker could move from:

Compromised Service A

to:

Database

and design controls to prevent it.

Exercise 5#

Threat-model a payment API using STRIDE.

Exercise 6#

Design a secure service-to-service architecture using mTLS.


76. Next Chapter#

Chapter 31 — Secure Distributed Systems#

Chapter 30 established the security fundamentals.

The next chapter will go deeper into security architecture for distributed systems, including:

  • distributed authentication
  • service identities
  • mTLS architecture
  • OAuth/OIDC in distributed systems
  • API gateways
  • service-to-service authorization
  • workload identity
  • distributed secrets management
  • key rotation
  • zero-trust architecture
  • network policies
  • secure microservices
  • tenant isolation
  • security boundaries
  • threat modeling distributed systems
  • attack paths
  • supply-chain security
  • secure event-driven systems
  • security for Kafka/message queues
  • security in Kubernetes
  • audit architecture
  • security incident handling
  • advanced interview questions

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 29 — Disaster RecoveryNext ChapterChapter 31 — Secure Distributed Systems
PrevNext