System DesignMastery
--Advanced Topics — Expert Level

Security in System Design

Duration৬০-৯০ মিনিট
LevelAdvanced
FocusSystem Security
001Why Security Matters

Security কেন Critical? System Design-এ Security First

⏱ ৯০-১২০ মিনিট🔐 Advanced Security🛡️ Phase 5 — Topic 1

System Design interview-এ security একটা overlooked topic — কিন্তু senior engineers সবসময় security-first mindset নিয়ে চিন্তা করেন। Data breach, unauthorized access, বা injection attack — এগুলো শুধু technical problem নয়, business existential threat

Facebook-এর Cambridge Analytica scandal, Equifax data breach (147M users), বা Bangladesh Bank heist ($81M) — সব ক্ষেত্রেই security oversight ছিল। একজন system designer হিসেবে আপনাকে attack surface বুঝতে হবে এবং defence in depth apply করতে হবে।

📌 CIA Triad — Security-এর তিন স্তম্ভ

Confidentiality (গোপনীয়তা): শুধু authorized users data access করতে পারবেন। Encryption, access control।

Integrity (অখণ্ডতা): Data unauthorized ভাবে modify হয়নি। Hash, digital signature।

Availability (প্রাপ্যতা): Authorized users সবসময় service পাবেন। DDoS protection, redundancy।

→ সব security decision এই তিনটির trade-off। Over-encryption করলেন availability কমে।

Attack Surface — System Design Security Overview

ATTACKERInternetAPI GATEWAYAuth + Rate LimitTLS terminationWAF / DDoSUSER SERVICEmTLS between servicesORDER SERVICERBAC / ABACPAY SERVICEPCI DSS + EncryptionDATABASEEncryption at restSecrets via VaultVAULTDynamic SecretsRotationAUTH SERVERJWT / OAuth2OpenID ConnectAttack vectorSecured channelInternal communication
002Authentication

Authentication — আপনি কে? JWT থেকে OAuth2

Authentication মানে identity verification — আপনি কে তা prove করুন। Modern systems-এ তিনটি major approach: Session-based, JWT (JSON Web Token), এবং OAuth2। প্রতিটার নিজস্ব use case আছে।

JWT Structure — header.payload.signature

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsInJvbGUiOiJhZG1pbiJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

HEADER

alg: RS256

typ: JWT

Algorithm + token type

PAYLOAD

sub: user_123

role: admin

exp: 1735689600

Claims — user data

SIGNATURE

HMAC_SHA256(

base64(header) +

"." +

base64(payload),

secret

)

auth.ts — JWT generation & verification
import jwt from 'jsonwebtoken';
import { Request, Response, NextFunction } from 'express';

const ACCESS_TOKEN_SECRET = process.env.JWT_SECRET!;
const REFRESH_TOKEN_SECRET = process.env.JWT_REFRESH_SECRET!;

// ─────────────────────────────────────────────
// JWT Token Generate করুন
// ─────────────────────────────────────────────
export function generateTokens(userId: string, role: string) {
    // Access token — short-lived (15 minutes)
    const accessToken = jwt.sign(
        { sub: userId, role, type: 'access' },
        ACCESS_TOKEN_SECRET,
        { expiresIn: '15m', algorithm: 'RS256' }
    );

    // Refresh token — long-lived (7 days), stored in DB
    const refreshToken = jwt.sign(
        { sub: userId, type: 'refresh' },
        REFRESH_TOKEN_SECRET,
        { expiresIn: '7d', algorithm: 'RS256' }
    );

    return { accessToken, refreshToken };
}

// ─────────────────────────────────────────────
// JWT Middleware — Request verify করুন
// ─────────────────────────────────────────────
export function authenticate(req: Request, res: Response, next: NextFunction) {
    // Authorization: Bearer <token>
    const authHeader = req.headers.authorization;
    if (!authHeader?.startsWith('Bearer ')) {
        return res.status(401).json({ error: 'No token provided' });
    }

    const token = authHeader.split(' ')[1];

    try {
        const payload = jwt.verify(token, ACCESS_TOKEN_SECRET) as {
            sub: string;
            role: string;
            exp: number;
        };

        // Attach user info to request
        (req as any).user = { id: payload.sub, role: payload.role };
        next();
    } catch (err) {
        if (err instanceof jwt.TokenExpiredError) {
            return res.status(401).json({ error: 'Token expired' });
        }
        return res.status(401).json({ error: 'Invalid token' });
    }
}

// ─────────────────────────────────────────────
// Python equivalent (FastAPI)
// ─────────────────────────────────────────────
/*
from jose import JWTError, jwt
from datetime import datetime, timedelta

SECRET_KEY = os.getenv("JWT_SECRET")
ALGORITHM = "RS256"

def create_access_token(user_id: str, role: str) -> str:
    payload = {
        "sub": user_id,
        "role": role,
        "exp": datetime.utcnow() + timedelta(minutes=15),
        "iat": datetime.utcnow(),
    }
    return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

def verify_token(token: str) -> dict:
    try:
        return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except JWTError:
        raise HTTPException(status_code=401, detail="Invalid token")
*/
Approachকীভাবে কাজ করেScalabilityBest ForDownside
Session-basedServer-side session store। Cookie-তে session ID।Sticky session দরকার বা shared RedisMonolith, server-rendered appsStateful — horizontal scaling কঠিন
JWTSelf-contained token। Server-side storage নেই।Excellent — statelessMicroservices, SPA, mobile appsToken revocation কঠিন। Size বড়।
OAuth2Third-party authorization। Delegation protocol।Delegated auth — scalable"Login with Google" type flowsComplex flow, setup overhead

⚠️ JWT Token কোথায় Store করবেন?

localStorage — AVOID: XSS attack-এ easily steal করা যায়। JavaScript দিয়ে access।

HttpOnly Cookie — RECOMMENDED: JavaScript access করতে পারে না। CSRF protection দরকার (SameSite=Strict)।

Memory (React state) — OK: Page refresh-এ logout। Refresh token HttpOnly cookie-তে রাখুন।

003OAuth2 & OIDC

OAuth2 & OpenID Connect — Delegated Authorization

OAuth2 হলো authorization framework — আপনি কাউকে আপনার হয়ে কিছু করার permission দিচ্ছ। "Login with Google" বা GitHub OAuth — এগুলো OAuth2। OpenID Connect (OIDC) হলো OAuth2-এর উপর identity layer — authentication add করে।

STEP 01[object Object]

Step 1 — User clicks "Login with Google"

App (Client) user-কে Google-এর Authorization Server-এ redirect করে। URL-এ থাকে: client_id, redirect_uri, scope, state, response_type=code। State parameter CSRF prevent করে।

STEP 02[object Object]

Step 2 — User Google-এ Login করে Consent দেয়

Google user-কে authenticate করে এবং permission চায় (email, profile access)। User consent করলেন Google একটা authorization code generate করে।

STEP 03[object Object]

Step 3 — Authorization Code App-এ Redirect হয়

Google আমাদের app-এর redirect_uri?code=AUTH_CODE&state=xyz এ redirect করে। এই code short-lived (~10 min)। Exposed হলেও একবার use করা যায়।

STEP 04[object Object]

Step 4 — Backend Code দিয়ে Token Exchange করে

App backend Google-এ POST করে: code + client_secret দিয়ে। Google দেয়: access_token, id_token (JWT), refresh_token। এটা server-side — client secret exposed হয় না।

STEP 05[object Object]

Step 5 — Access Token দিয়ে Resource Access করুন

Access token দিয়ে Google APIs call করুন (email, calendar)। id_token (OIDC) দিয়ে user identity verify করুন। Token expire হলে refresh token দিয়ে নতুন access token নাও।

Grant Typeকখন Use করবেনSecurity LevelExample
Authorization CodeWeb apps — server-side code exchangeHighest"Login with Google" — web app
Authorization Code + PKCESPA, Mobile apps — no client secretHighReact SPA, iOS/Android app
Client CredentialsMachine-to-machine, no user involvedMediumMicroservice A calls Microservice B
Resource Owner PasswordLegacy — highly trusted first-party appsLow — AVOIDDeprecated — direct username/password

📌 OAuth2 vs OpenID Connect পার্থক্য

OAuth2:Authorization protocol — "এই app-কে আমার Gmail read করতে দিন।" Access control, delegation।

OpenID Connect:OAuth2-এর উপর authentication layer — "এই user কে?" id_token (JWT) দেয় যাতে user info থাকে।

→ Rule: OAuth2 = Authorization। OIDC = Authentication। Login flow-এ OIDC use করুন।

004Authorization

Authorization — আপনি কী করতে পারবেন? RBAC vs ABAC

Authentication verify করে "আপনি কে", Authorization decide করে "আপনি কী করতে পারবেন"। দুটো major model: RBAC (Role-Based Access Control) এবং ABAC (Attribute-Based Access Control)।

FeatureRBACABACকোনটা কখন?
DefinitionRole দিয়ে access। admin, user, moderator।Attributes দিয়ে access। department, time, location।
GranularityCoarse-grained — role levelFine-grained — attribute levelComplex rules = ABAC
ComplexitySimple to implementPolicy-based, complex rulesSimple teams = RBAC
Exampleadmin পারে delete করতে, user পারে নাFinance dept + working hours + own documentsBanks, healthcare = ABAC
PerformanceFast — role checkSlower — multiple attribute evaluationHigh traffic = RBAC preferred
Real-world useGitHub (owner/member/outside), AWS IAM rolesAWS IAM policies, Google Cloud IAM conditionsMost systems = hybrid
authorization-middleware.ts
import { Request, Response, NextFunction } from 'express';

// ─────────────────────────────────────────────
// RBAC — Role-Based Authorization Middleware
// ─────────────────────────────────────────────
export function requireRole(...roles: string[]) {
    return (req: Request, res: Response, next: NextFunction) => {
        const user = (req as any).user;

        if (!user) {
            return res.status(401).json({ error: 'Unauthenticated' });
        }

        if (!roles.includes(user.role)) {
            return res.status(403).json({
                error: 'Forbidden',
                required: roles,
                current: user.role,
            });
        }

        next();
    };
}

// Usage:
// app.delete('/posts/:id', authenticate, requireRole('admin', 'moderator'), deletePost);
// app.get('/reports', authenticate, requireRole('admin'), getReports);

// ─────────────────────────────────────────────
// ABAC — Attribute-Based Authorization
// ─────────────────────────────────────────────
interface Policy {
    action: string;
    condition: (user: any, resource: any, env: any) => boolean;
}

const policies: Policy[] = [
    {
        action: 'document:read',
        condition: (user, resource, env) =>
            // User নিজের department-এর document read করতে পারবেন
            // অথবা admin সবসময় পারবেন
            user.department === resource.department || user.role === 'admin',
    },
    {
        action: 'document:write',
        condition: (user, resource, env) =>
            // শুধু working hours-এ এবং নিজের document
            user.id === resource.ownerId &&
            env.hour >= 9 &&
            env.hour <= 18,
    },
    {
        action: 'report:export',
        condition: (user, resource, env) =>
            // Finance dept + senior level + weekday only
            user.department === 'finance' &&
            user.level >= 3 &&
            env.dayOfWeek >= 1 && env.dayOfWeek <= 5,
    },
];

export function checkPolicy(action: string, resource: any) {
    return (req: Request, res: Response, next: NextFunction) => {
        const user = (req as any).user;
        const env = {
            hour: new Date().getHours(),
            dayOfWeek: new Date().getDay(),
            ip: req.ip,
        };

        const policy = policies.find(p => p.action === action);
        if (!policy || !policy.condition(user, resource, env)) {
            return res.status(403).json({ error: 'Policy denied' });
        }
        next();
    };
}

💡 Principle of Least Privilege

সবসময় minimum permission দিন। একটা microservice শুধু সেটাই access করতে পারবেন যা তার কাজে দরকার। Database service account-এর শুধু SELECT permission, না সব tables-এ full access। এটা breach হলে damage কমে।

005Encryption & TLS

Encryption & TLS/mTLS — Data Protect করুন

Encryption দুই ধরনের: Encryption in Transit (data move করার সময়) এবং Encryption at Rest (storage-এ)। TLS handle করে transit encryption। mTLS microservices-এর মধ্যে mutual authentication নিশ্চিত করে।

TypeSymmetricAsymmetric
Keyএকটাই key — encrypt ও decryptPublic key (encrypt) + Private key (decrypt)
SpeedFast — bulk data জন্য idealSlow — key exchange জন্য use করুন
AlgorithmAES-256, ChaCha20RSA-2048, ECDSA, Ed25519
ProblemKey distribution — কীভাবে share করবেন?Computationally expensive
HTTPS-এ ব্যবহারData transfer phase — AES session keyTLS Handshake — key exchange

TLS Handshake Flow — HTTPS Connection

CLIENTSERVERClientHello (TLS version, cipher suites, random)ServerHello + Certificate (Public Key)Pre-master Secret (encrypted with Server Public Key)↓ derive session keys↓ derive session keysFinished (MAC verify)Finished (MAC verify)Application Data (AES-256 symmetric encryption)ASYMMETRIC (key exchange)SYMMETRIC (data)TLS 1.3 — 1-RTT handshake। TLS 1.2 — 2-RTT

📌 mTLS — Mutual TLS (Service-to-Service)

Regular TLS-এ শুধু server certificate present করে। mTLS-এ client ও server উভয়ই certificate present করে — mutual authentication।

Microservices-এ Order Service কি সত্যিই Payment Service? mTLS নিশ্চিত করে। Service mesh (Istio, Linkerd) automatically mTLS handle করে।

→ Zero Trust Architecture-এর core component। Internal network-ও trust করুন না।

006Zero Trust Architecture

Zero Trust — "Never Trust, Always Verify"

Traditional security model বলতো: "Castle and Moat" — ভেতরে যা আছে সব trusted। Zero Trust বলে: "Never trust, always verify" — internal network-ও trust করুন না। প্রতিটা request verify করুন।

Perimeter Security vs Zero Trust

PERIMETER SECURITY (OLD)Firewall / VPNService AService BDatabaseAdmin Panelভেতরে সব trusted — attacker ঢুকলে সব access✗ Lateral movement possibleZERO TRUST (NEW)Service AmTLS + JWTverify every reqService BmTLS + JWTverify every reqDatabaseLeast privilegeDynamic credsAdmin PanelMFA requiredaudit logপ্রতিটা service isolated — breach confined✓ Lateral movement blocked

✅ Zero Trust Implementation Checklist

প্রতিটা service request-এ identity verify করুন (mTLS)
Least privilege — minimum necessary access
Network segment করুন — microservice isolation
সব traffic encrypt করুন (internal ও external)
Continuous monitoring — anomaly detection
Dynamic credentials — Vault secrets rotation
Multi-Factor Authentication সব admin access-এ
Audit log — সব action trackable হতে হবে
Device health check — endpoint security
Just-in-time access — temporary elevated privileges

🎯 Zero Trust in Interview

Interview-এ বলুন: "আমি assume করি network already compromised" — এটা Zero Trust mindset। Internal service calls-এ mTLS, JWT validation, এবং Vault-based credential rotation mention করলেন senior-level approach দেখা যায়।

007Secrets Management

Secrets Management — HashiCorp Vault & AWS Secrets Manager

Database passwords, API keys, TLS certificates — এগুলো secrets। Production systems-এ secrets hardcode করা বা .env file-এ রাখা catastrophic হতে পারে। Dedicated secrets management tools দরকার: HashiCorp Vault এবং AWS Secrets Manager

⚠️ Hardcoded Credentials — Never Do This!

GitHub-এ secret leak হলে automated bots minutes-এর মধ্যে exploit করে। 2023-এ Toyota-র AWS key GitHub-এ ছিল — লক্ষ customer data exposed।

// ❌ NEVER DO THIS
const DB_PASSWORD = "super_secret_123";
const API_KEY = "sk-prod-abc123xyz";

Git history-তে থাকলেও danger — secret rotate করতে হবে। git-secrets বা truffleHog দিয়ে scan করুন।

vault-secrets.ts — Dynamic Secret Rotation
import axios from 'axios';
import { Pool } from 'pg';

const VAULT_ADDR = process.env.VAULT_ADDR!;
const VAULT_TOKEN = process.env.VAULT_TOKEN!; // Service token (short-lived)

// ─────────────────────────────────────────────
// HashiCorp Vault — Dynamic Database Credentials
// ─────────────────────────────────────────────
interface VaultDBCreds {
    username: string;
    password: string;
    lease_duration: number; // seconds
    lease_id: string;
}

async function getDynamicDBCredentials(): Promise<VaultDBCreds> {
    // Vault generates temporary DB credentials on demand
    const response = await axios.get(
        `${VAULT_ADDR}/v1/database/creds/my-role`,
        { headers: { 'X-Vault-Token': VAULT_TOKEN } }
    );

    return {
        username: response.data.data.username,   // e.g., "v-service-xYz123"
        password: response.data.data.password,
        lease_duration: response.data.lease_duration, // e.g., 3600 (1 hour)
        lease_id: response.data.lease_id,
    };
}

// ─────────────────────────────────────────────
// Auto-Rotating DB Connection Pool
// ─────────────────────────────────────────────
class ManagedDBPool {
    private pool: Pool | null = null;
    private leaseExpiry: number = 0;
    private leaseId: string = '';

    async getPool(): Promise<Pool> {
        const now = Math.floor(Date.now() / 1000);

        // Renew credentials 5 minutes before expiry
        if (!this.pool || now >= this.leaseExpiry - 300) {
            await this.rotateCredentials();
        }

        return this.pool!;
    }

    private async rotateCredentials() {
        console.log('[Vault] Fetching new DB credentials...');

        // Revoke old lease first
        if (this.leaseId) {
            await axios.put(
                `${VAULT_ADDR}/v1/sys/leases/revoke`,
                { lease_id: this.leaseId },
                { headers: { 'X-Vault-Token': VAULT_TOKEN } }
            );
        }

        const creds = await getDynamicDBCredentials();
        this.leaseId = creds.lease_id;
        this.leaseExpiry = Math.floor(Date.now() / 1000) + creds.lease_duration;

        // Destroy old pool gracefully
        if (this.pool) {
            await this.pool.end();
        }

        this.pool = new Pool({
            host: process.env.DB_HOST,
            database: process.env.DB_NAME,
            user: creds.username,    // Vault-generated temp user
            password: creds.password, // Vault-generated temp password
            port: 5432,
            ssl: { rejectUnauthorized: true },
        });

        console.log(`[Vault] DB creds rotated. Expires in ${creds.lease_duration}s`);
    }
}

// ─────────────────────────────────────────────
// AWS Secrets Manager Alternative
// ─────────────────────────────────────────────
import {
    SecretsManagerClient,
    GetSecretValueCommand,
} from '@aws-sdk/client-secrets-manager';

const secretsClient = new SecretsManagerClient({ region: 'ap-southeast-1' });

async function getSecret(secretName: string): Promise<Record<string, string>> {
    const cmd = new GetSecretValueCommand({ SecretId: secretName });
    const response = await secretsClient.send(cmd);

    if (!response.SecretString) throw new Error('Secret not found');
    return JSON.parse(response.SecretString);
}

// Usage:
// const dbCreds = await getSecret('prod/myapp/db');
// const { username, password, host } = dbCreds;
FeatureHashiCorp VaultAWS Secrets ManagerGCP Secret Manager
Dynamic Secrets✓ DB, SSH, PKILimited (RDS only)✗ Static only
Auto Rotation✓ Built-in✓ Lambda-based✓ Cloud Functions
Multi-cloud✓ Any cloud / on-premAWS onlyGCP only
PricingOpen source + Enterprise$0.40/secret/month$0.06/10K access
Best ForComplex multi-cloud setupsAWS-native appsGCP-native apps

💡 Secret Scanning — Prevent Leaks Early

Git pre-commit hook-এ git-secrets বা detect-secrets run করুন। CI/CD pipeline-এ TruffleHog বা GitLeaks add করুন। GitHub Advanced Security automatically secret scan করে। একবার push হলে history-তে থাকে — rotate করতে হবে।

008OWASP & Interview Tips

OWASP Top 10 & Security Interview Tips

OWASP (Open Web Application Security Project) প্রতি কয়েক বছরে web security-র top risks publish করে। System design interview-এ এগুলো জানা থাকলে security discussion অনেক productive হয়।

#Vulnerabilityকী হয়?MitigationReal Example
#1Broken Access ControlUnauthorized user অন্যের data access করতে পারেRBAC/ABAC, server-side check, JWT validationIDOR — /users/123 → /users/456
#2Cryptographic FailuresWeak/no encryption — data exposedTLS everywhere, AES-256, bcrypt passwordsMD5 password hash, HTTP instead of HTTPS
#3Injection (SQL, NoSQL, LDAP)Malicious input database execute করেPrepared statements, parameterized queries, ORMSELECT * FROM users WHERE id='1 OR 1=1'
#4Insecure DesignSecurity design-এ না থাকলে পরে fix কঠিনThreat modeling, security by design, code reviewRate limiting না থাকলে brute force possible
#7XSS (Cross-Site Scripting)Malicious JS inject করে victim browser-এ run হয়Output encoding, CSP headers, HttpOnly cookiesStored XSS: comment box এ <script>steal()</script>

🎯 Security Interview Questions — Pattern Guide

Q: আপনি API design করার সময় কোন security layer গুলো add করবেন?

A:API Gateway তে: TLS termination, rate limiting, JWT validation, WAF। Service level এ: mTLS, RBAC, input validation। DB level এ: encryption at rest, Vault credentials।

Q: User password কীভাবে store করবেন?

A:Never plaintext। bcrypt বা Argon2 দিয়ে hash করুন (cost factor ≥ 12)। Salt automatically added। Rainbow table attack defend হয়। MD5/SHA-1 avoid করুন।

Q: Microservices এ service-to-service auth কীভাবে করবেন?

A:mTLS (mutual TLS) — service mesh (Istio) automatically handle করে। অথবা OAuth2 Client Credentials flow — service identity।

Q: Rate limiting কেন দরকার এবং কোথায় implement করবেন?

A:Brute force, DDoS, credential stuffing prevent করতে। API Gateway-এ (per IP, per user)। Redis দিয়ে sliding window counter। 429 Too Many Requests।

💡 Security Interview-এর Common Patterns

1. Defence in Depth: একটা layer fail হলেও অন্যগুলো protect করে। TLS + JWT + RBAC + audit log।

2. Threat Modeling:"এই system-এ কে attack করতে পারে?" — external attacker, malicious insider, compromised service।

3. Security != Complexity: Simple এবং correct better than complex এবং insecure।

4. Zero Trust Mindset:"আমি internal network trust করি না" — mTLS, service identity।

5. Fail Secure: System fail হলে secure state-এ যাবেন — deny by default।

CIA Triad

Security foundation

JWT + mTLS

Auth stack

Zero Trust

Architecture model

Vault

Secrets management

OWASP Top 10

Vulnerability catalog

RBAC/ABAC

Authorization models

TLS 1.3

Transit encryption

AES-256

Data encryption

009Lesson Summary

SUMMARY — আজকে যা শিখলাম

Conceptকী করেKey Tool/ProtocolInterview Relevance
JWTStateless authentication token। Self-contained claims।RS256 signature, HttpOnly cookieVery High — every API design
OAuth2 / OIDCDelegated authorization + authentication।Authorization Code + PKCEHigh — third-party integration
mTLSMutual authentication — client + server both verify।Istio service mesh, certificatesHigh — microservices security
RBAC / ABACWho can do what। Role or attribute-based।Middleware, Policy engineHigh — authorization design
Zero TrustNever trust, always verify। Internal ও external।mTLS + identity-aware proxyHigh — architecture principle
VaultDynamic secrets, auto-rotation। No hardcoded creds।HashiCorp Vault, AWS Secrets ManagerMedium-High — production systems
OWASP Top 10Common vulnerabilities catalog। Mitigation guide।Input validation, prepared statements, CSPHigh — security interview staple
010Knowledge Check
011Assignments
012Practical Lab