Security in System Design
Security কেন Critical? System Design-এ Security First
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
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
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
)
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 | কীভাবে কাজ করে | Scalability | Best For | Downside |
|---|---|---|---|---|
| Session-based | Server-side session store। Cookie-তে session ID। | Sticky session দরকার বা shared Redis | Monolith, server-rendered apps | Stateful — horizontal scaling কঠিন |
| JWT | Self-contained token। Server-side storage নেই। | Excellent — stateless | Microservices, SPA, mobile apps | Token revocation কঠিন। Size বড়। |
| OAuth2 | Third-party authorization। Delegation protocol। | Delegated auth — scalable | "Login with Google" type flows | Complex 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-তে রাখুন।
OAuth2 & OpenID Connect — Delegated Authorization
OAuth2 হলো authorization framework — আপনি কাউকে আপনার হয়ে কিছু করার permission দিচ্ছ। "Login with Google" বা GitHub OAuth — এগুলো OAuth2। OpenID Connect (OIDC) হলো OAuth2-এর উপর identity layer — authentication add করে।
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 2 — User Google-এ Login করে Consent দেয়
Google user-কে authenticate করে এবং permission চায় (email, profile access)। User consent করলেন Google একটা authorization code generate করে।
Step 3 — Authorization Code App-এ Redirect হয়
Google আমাদের app-এর redirect_uri?code=AUTH_CODE&state=xyz এ redirect করে। এই code short-lived (~10 min)। Exposed হলেও একবার use করা যায়।
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 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 Level | Example |
|---|---|---|---|
| Authorization Code | Web apps — server-side code exchange | Highest | "Login with Google" — web app |
| Authorization Code + PKCE | SPA, Mobile apps — no client secret | High | React SPA, iOS/Android app |
| Client Credentials | Machine-to-machine, no user involved | Medium | Microservice A calls Microservice B |
| Resource Owner Password | Legacy — highly trusted first-party apps | Low — AVOID | Deprecated — 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 করুন।
Encryption & TLS/mTLS — Data Protect করুন
Encryption দুই ধরনের: Encryption in Transit (data move করার সময়) এবং Encryption at Rest (storage-এ)। TLS handle করে transit encryption। mTLS microservices-এর মধ্যে mutual authentication নিশ্চিত করে।
| Type | Symmetric | Asymmetric |
|---|---|---|
| Key | একটাই key — encrypt ও decrypt | Public key (encrypt) + Private key (decrypt) |
| Speed | Fast — bulk data জন্য ideal | Slow — key exchange জন্য use করুন |
| Algorithm | AES-256, ChaCha20 | RSA-2048, ECDSA, Ed25519 |
| Problem | Key distribution — কীভাবে share করবেন? | Computationally expensive |
| HTTPS-এ ব্যবহার | Data transfer phase — AES session key | TLS Handshake — key exchange |
TLS Handshake Flow — HTTPS Connection
📌 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 করুন না।
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
✅ Zero Trust Implementation Checklist
🎯 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 দেখা যায়।
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 করুন।
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;| Feature | HashiCorp Vault | AWS Secrets Manager | GCP Secret Manager |
|---|---|---|---|
| Dynamic Secrets | ✓ DB, SSH, PKI | Limited (RDS only) | ✗ Static only |
| Auto Rotation | ✓ Built-in | ✓ Lambda-based | ✓ Cloud Functions |
| Multi-cloud | ✓ Any cloud / on-prem | AWS only | GCP only |
| Pricing | Open source + Enterprise | $0.40/secret/month | $0.06/10K access |
| Best For | Complex multi-cloud setups | AWS-native apps | GCP-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 করতে হবে।
OWASP Top 10 & Security Interview Tips
OWASP (Open Web Application Security Project) প্রতি কয়েক বছরে web security-র top risks publish করে। System design interview-এ এগুলো জানা থাকলে security discussion অনেক productive হয়।
| # | Vulnerability | কী হয়? | Mitigation | Real Example |
|---|---|---|---|---|
| #1 | Broken Access Control | Unauthorized user অন্যের data access করতে পারে | RBAC/ABAC, server-side check, JWT validation | IDOR — /users/123 → /users/456 |
| #2 | Cryptographic Failures | Weak/no encryption — data exposed | TLS everywhere, AES-256, bcrypt passwords | MD5 password hash, HTTP instead of HTTPS |
| #3 | Injection (SQL, NoSQL, LDAP) | Malicious input database execute করে | Prepared statements, parameterized queries, ORM | SELECT * FROM users WHERE id='1 OR 1=1' |
| #4 | Insecure Design | Security design-এ না থাকলে পরে fix কঠিন | Threat modeling, security by design, code review | Rate limiting না থাকলে brute force possible |
| #7 | XSS (Cross-Site Scripting) | Malicious JS inject করে victim browser-এ run হয় | Output encoding, CSP headers, HttpOnly cookies | Stored 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
SUMMARY — আজকে যা শিখলাম
| Concept | কী করে | Key Tool/Protocol | Interview Relevance |
|---|---|---|---|
| JWT | Stateless authentication token। Self-contained claims। | RS256 signature, HttpOnly cookie | Very High — every API design |
| OAuth2 / OIDC | Delegated authorization + authentication। | Authorization Code + PKCE | High — third-party integration |
| mTLS | Mutual authentication — client + server both verify। | Istio service mesh, certificates | High — microservices security |
| RBAC / ABAC | Who can do what। Role or attribute-based। | Middleware, Policy engine | High — authorization design |
| Zero Trust | Never trust, always verify। Internal ও external। | mTLS + identity-aware proxy | High — architecture principle |
| Vault | Dynamic secrets, auto-rotation। No hardcoded creds। | HashiCorp Vault, AWS Secrets Manager | Medium-High — production systems |
| OWASP Top 10 | Common vulnerabilities catalog। Mitigation guide। | Input validation, prepared statements, CSP | High — security interview staple |