Security and OWASP
Table of Contents
- OWASP Top 10 (2021)
- Broken Access Control
- Cryptographic Failures
- Injection
- Security Misconfiguration
- Authentication & Authorization
- Secure Coding Practices
- Interview Questions
- Senior / Principal — Real World Security Scenarios
- Insecure Design and Threat Modelling
- Vulnerable and Outdated Components
- API Security and Data Access
- Tokens, OAuth and Browser Security
- Passwords, Secrets and Abuse Protection
- Senior / Principal — API and Application Security Scenarios
OWASP Top 10 (2021)
┌─────────────────────────────────────────────────────────────┐
│ OWASP TOP 10 (2021) │
├─────────────────────────────────────────────────────────────┤
│ │
│ A01 │ Broken Access Control │
│ A02 │ Cryptographic Failures │
│ A03 │ Injection │
│ A04 │ Insecure Design │
│ A05 │ Security Misconfiguration │
│ A06 │ Vulnerable Components │
│ A07 │ Authentication Failures │
│ A08 │ Software Integrity Failures │
│ A09 │ Logging & Monitoring Failures │
│ A10 │ Server-Side Request Forgery (SSRF) │
│ │
└─────────────────────────────────────────────────────────────┘
Broken Access Control
Overview
Access control enforces policy such that users cannot act outside of their intended permissions. Failures typically lead to unauthorized information disclosure, modification, or destruction.
Common Vulnerabilities
# ============================================
# VULNERABLE CODE (DO NOT USE)
# ============================================
# ❌ Broken Access Control Examples
# 1. Insecure Direct Object Reference (IDOR)
@app.route('/api/users/<user_id>')
def get_user(user_id):
# User can access ANY user by guessing IDs!
user = User.query.get(user_id)
return jsonify(user)
# 2. Missing Authorization Check
@app.route('/api/admin/delete_user', methods=['POST'])
def delete_user():
# No check if user is admin!
user_id = request.json['user_id']
User.query.filter_by(id=user_id).delete()
return '', 204
# 3. Method-Based Access Control Bypass
@app.route('/api/users', methods=['GET'])
@login_required
def get_users():
# GET is protected but...
return jsonify(users)
@app.route('/api/users', methods=['POST'])
def create_user():
# POST might not be!
return jsonify({"id": 1})
# 4. Horizontal Privilege Escalation
@app.route('/api/orders/<order_id>')
@login_required
def get_order(order_id):
# User can view OTHER users' orders
order = Order.query.get(order_id)
return jsonify(order)
Secure Implementation
# ============================================
# SECURE CODE (CORRECT)
# ============================================
from functools import wraps
from flask import abort, g
# 1. Use authorization decorators
def require_permission(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.has_permission(permission):
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
@app.route('/api/admin/users')
@login_required
@require_permission('users:read')
def list_users():
return jsonify(User.query.all())
# 2. Use relationship-based access control
@app.route('/api/users/<int:user_id>')
@login_required
def get_user(user_id):
# Check if user is accessing their own data
if current_user.id != user_id and not current_user.is_admin:
# Also check resource-level permissions
user = User.query.get_or_404(user_id)
if not current_user.can_access(user):
abort(403)
return jsonify(user)
# 3. Use policy-based access control
class AccessControl:
@staticmethod
def can_read(user, resource) -> bool:
# Organization-level access
if user.organization_id == resource.organization_id:
return True
return False
@staticmethod
def can_write(user, resource) -> bool:
if user.is_admin:
return True
if user.organization_id == resource.organization_id:
return resource.is_editable_by(user)
return False
@app.route('/api/documents/<int:doc_id>')
@login_required
def get_document(doc_id):
doc = Document.query.get_or_404(doc_id)
if not AccessControl.can_read(current_user, doc):
abort(403)
return jsonify(doc)
# 4. Horizontal and vertical access control
@app.route('/api/orders/<int:order_id>')
@login_required
def get_order(order_id):
order = Order.query.get_or_404(order_id)
# Horizontal: User can only see their own orders
if order.user_id != current_user.id:
# Check if user has admin role
if not current_user.has_role('admin'):
abort(403)
return jsonify(order)
# 5. Use declarative security in frameworks
# Django example
class OrderView(LoginRequiredMixin, PermissionRequiredMixin, DetailView):
model = Order
template_name = 'order_detail.html'
permission_required = 'orders.view_order'
def get_queryset(self):
# Automatically filter to user's orders
if self.request.user.is_superuser:
return Order.objects.all()
return Order.objects.filter(user=self.request.user)
Access Control Patterns
# RBAC (Role-Based Access Control)
class Role:
ADMIN = 'admin'
MANAGER = 'manager'
USER = 'user'
GUEST = 'guest'
PERMISSIONS = {
Role.ADMIN: ['*'], # All permissions
Role.MANAGER: [
'users:read', 'users:update',
'orders:read', 'orders:update', 'orders:create',
'reports:read', 'reports:create'
],
Role.USER: [
'orders:read:own',
'profile:read', 'profile:update'
],
Role.GUEST: ['profile:read']
}
# ABAC (Attribute-Based Access Control)
class Policy:
@staticmethod
def evaluate(user, resource, action) -> bool:
context = {
'user': user,
'resource': resource,
'action': action,
'time': datetime.now(),
'ip': request.remote_addr
}
# Example policy: Allow access during work hours
if user.department == 'engineering':
if 9 <= context['time'].hour <= 18:
return True
# Example policy: IP-based restriction
if resource.classification == 'top-secret':
if context['ip'].startswith('10.0.0.'):
return True
return False
# Zero Trust Architecture
class ZeroTrustAccess:
"""Never trust, always verify"""
@staticmethod
def verify_identity(user) -> bool:
# Multi-factor authentication
if not user.mfa_enabled:
return False
if not user.has_valid_session():
return False
return True
@staticmethod
def verify_device(user, device) -> bool:
# Device compliance check
if not device.is_managed:
return False
if not device.has_valid_certificate():
return False
return True
@staticmethod
def verify_context(user, resource) -> bool:
# Context-aware access
if user.location != resource.allowed_location:
if not user.is_manager:
return False
return True
Cryptographic Failures
Common Vulnerabilities
# ============================================
# VULNERABLE CRYPTO CODE (DO NOT USE)
# ============================================
# ❌ Weak hashing algorithms
import hashlib
def hash_password(password):
return hashlib.md5(password.encode()).hexdigest() # NEVER USE MD5!
# ❌ Using custom crypto
def encrypt_data(data, key):
# NEVER create your own crypto!
return base64.b64encode(data ^ key) # INSECURE!
# ❌ Hardcoded secrets
API_KEY = "sk_live_abc123xyz" # NEVER!
# ❌ Weak encryption
from Crypto.Cipher import AES
cipher = AES.new(key, AES.MODE_ECB) # ECB is insecure!
# ❌ Not using TLS
requests.get("http://api.example.com/data") # HTTP is insecure!
Secure Implementation
# ============================================
# SECURE CRYPTO CODE (CORRECT)
# ============================================
import bcrypt
import hashlib
import secrets
import os
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
# 1. Secure Password Hashing with bcrypt
def hash_password(password: str) -> str:
"""Hash password using bcrypt with salt"""
salt = bcrypt.gensalt(rounds=12)
hashed = bcrypt.hashpw(password.encode(), salt)
return hashed.decode()
def verify_password(password: str, hashed: str) -> bool:
"""Verify password against bcrypt hash"""
return bcrypt.checkpw(password.encode(), hashed.encode())
# 2. Using Fernet for symmetric encryption
class SecureEncryptor:
def __init__(self, key: bytes = None):
if key:
self.cipher = Fernet(key)
else:
self.key = Fernet.generate_key()
self.cipher = Fernet(self.key)
def encrypt(self, data: str) -> bytes:
"""Encrypt string data"""
return self.cipher.encrypt(data.encode())
def decrypt(self, encrypted_data: bytes) -> str:
"""Decrypt to string"""
return self.cipher.decrypt(encrypted_data).decode()
def encrypt_file(self, input_path: str, output_path: str):
"""Encrypt file"""
with open(input_path, 'rb') as f:
data = f.read()
encrypted = self.cipher.encrypt(data)
with open(output_path, 'wb') as f:
f.write(encrypted)
# 3. Deriving keys from passwords
def derive_key(password: str, salt: bytes = None) -> tuple:
"""Derive key using PBKDF2"""
if salt is None:
salt = os.urandom(16)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=600_000, # OWASP guidance for PBKDF2-HMAC-SHA256
)
key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
return key, salt
# 4. Secure random token generation
def generate_token(length: int = 32) -> str:
"""Generate cryptographically secure token"""
return secrets.token_urlsafe(length)
def generate_api_key() -> str:
"""Generate API key with prefix"""
prefix = "sk_live_"
random_part = secrets.token_urlsafe(32)
return f"{prefix}{random_part}"
# 5. Secure comparison
import hmac
def secure_compare(a: bytes, b: bytes) -> bool:
"""Constant-time comparison to prevent timing attacks"""
return hmac.compare_digest(a, b)
# 6. Hash-based message authentication
def create_hmac(data: str, key: str) -> str:
"""Create HMAC for message authentication"""
return hmac.new(
key.encode(),
data.encode(),
hashlib.sha256
).hexdigest()
def verify_hmac(data: str, key: str, expected_hmac: str) -> bool:
"""Verify HMAC using constant-time comparison"""
actual_hmac = create_hmac(data, key)
return hmac.compare_digest(actual_hmac, expected_hmac)
# 7. Hashing for integrity verification (not passwords)
def hash_file(filepath: str) -> str:
"""Calculate SHA-256 hash of file"""
sha256_hash = hashlib.sha256()
with open(filepath, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
# 8. Secure secret storage pattern
import json
from pathlib import Path
class SecretManager:
"""Manage secrets securely using environment variables"""
@staticmethod
def get_secret(name: str, default: str = None) -> str:
"""Get secret from environment"""
value = os.getenv(name)
if value is None and default is None:
raise ValueError(f"Secret {name} not found")
return value or default
@staticmethod
def get_database_url() -> str:
"""Get database URL from secrets"""
return SecretManager.get_secret('DATABASE_URL')
@staticmethod
def get_api_keys() -> dict:
"""Get all API keys"""
return {
'stripe': SecretManager.get_secret('STRIPE_API_KEY'),
'aws': {
'access_key': SecretManager.get_secret('AWS_ACCESS_KEY_ID'),
'secret_key': SecretManager.get_secret('AWS_SECRET_ACCESS_KEY'),
}
}
Injection
SQL Injection
# ============================================
# VULNERABLE CODE (SQL INJECTION)
# ============================================
# ❌ String concatenation (VULNERABLE!)
@app.route('/api/users')
def get_users():
user_id = request.args.get('id')
query = f"SELECT * FROM users WHERE id = {user_id}" # VULNERABLE!
cursor.execute(query)
# ❌ Using string formatting
query = "SELECT * FROM users WHERE email = '%s'" % email # VULNERABLE!
# ❌ Order by injection
query = "SELECT * FROM users ORDER BY %s" % column # VULNERABLE!
Secure Implementation
# ============================================
# SECURE CODE (SQL INJECTION PREVENTION)
# ============================================
from sqlalchemy import text
from sqlalchemy.orm import Session
# 1. Parameterized queries
@app.route('/api/users/<int:user_id>')
def get_user(user_id):
# Using SQLAlchemy ORM (safe)
user = db.session.query(User).filter_by(id=user_id).first()
return jsonify(user)
# 2. Raw parameterized queries
@app.route('/api/users')
def get_users():
user_id = request.args.get('id', type=int)
# Parameterized query (safe)
result = db.session.execute(
text("SELECT * FROM users WHERE id = :id"),
{"id": user_id}
)
return jsonify([dict(row._mapping) for row in result])
# 3. Safe order by using whitelist
ALLOWED_SORT_COLUMNS = {
'name': 'name',
'email': 'email',
'created_at': 'created_at'
}
@app.route('/api/users')
def list_users():
sort = request.args.get('sort', 'name')
direction = request.args.get('direction', 'asc')
# Validate and whitelist
column = ALLOWED_SORT_COLUMNS.get(sort, 'name')
if direction.lower() not in ['asc', 'desc']:
direction = 'asc'
query = db.session.query(User).order_by(
getattr(User, column).asc() if direction == 'asc'
else getattr(User, column).desc()
)
return jsonify(query.all())
# 4. ORM query builder (always parameterized)
class UserRepository:
def find_by_email(self, email: str) -> User:
# SQLAlchemy automatically parameterizes
return User.query.filter(User.email == email).first()
def find_with_filters(self, **filters) -> list:
query = User.query
for key, value in filters.items():
if hasattr(User, key):
query = query.filter(getattr(User, key) == value)
return query.all()
def search(self, term: str) -> list:
# Safe LIKE query with parameterization
return User.query.filter(
User.name.ilike(f"%{term}%")
).all()
NoSQL Injection (MongoDB)
# ============================================
# MONGODB INJECTION PREVENTION
# ============================================
import bcrypt
from bson import ObjectId
# ❌ VULNERABLE: JSON body values passed straight into the query
@app.route('/api/login', methods=['POST'])
def login():
data = request.get_json()
# Attacker sends {"username": "admin", "password": {"$ne": ""}}
# and the operator dict matches any password.
user = db.users.find_one({"username": data["username"], "password": data["password"]})
# ✅ SECURE: enforce types before building the query
@app.route('/api/login', methods=['POST'])
def login_secure():
data = request.get_json()
username, password = data.get("username"), data.get("password")
if not isinstance(username, str) or not isinstance(password, str):
abort(400) # reject operator dicts and other non-string values
user = db.users.find_one({"username": username})
if user is None or not bcrypt.checkpw(password.encode(), user["password_hash"]):
abort(401)
return jsonify({"id": str(user["_id"])})
# For ObjectId queries
@app.route('/api/users/<user_id>')
def get_user_by_id(user_id):
try:
# Validate ObjectId format
user = db.users.find_one({"_id": ObjectId(user_id)})
return jsonify(user)
except:
abort(400)
# Input validation for complex queries
def sanitize_query(query: dict) -> dict:
"""Sanitize user input for MongoDB queries"""
# Remove $ characters that could be injection
sanitized = {}
for key, value in query.items():
if key.startswith('$'):
continue # Reject operators from user input
sanitized[key] = value
return sanitized
Command Injection
# ❌ VULNERABLE: Command injection
import os
@app.route('/ping')
def ping_host():
host = request.args.get('host')
# Attacker can run: host=google.com; cat /etc/passwd
os.system(f"ping -c 1 {host}")
# ✅ SECURE: Use subprocess safely
import subprocess
@app.route('/ping')
def ping_host():
host = request.args.get('host')
# Whitelist validation
import re
if not re.match(r'^[a-zA-Z0-9.-]+$', host):
abort(400)
# subprocess with list (safe)
result = subprocess.run(
['ping', '-c', '1', host],
capture_output=True,
text=True,
timeout=5
)
return result.stdout
Security Misconfiguration
Hardening Checklist
# ============================================
# SECURITY HEADERS
# ============================================
# All responses should include these headers:
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 0 # legacy XSS filter is deprecated; disable it and rely on CSP
Strict-Transport-Security: max-age=31536000; includeSubDomains
Content-Security-Policy: default-src 'self'
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: geolocation=(), microphone=()
# ============================================
# FLASK SECURITY CONFIGURATION
# ============================================
from flask import Flask
from flask_talisman import Talisman
app = Flask(__name__)
# Security headers
Talisman(app,
content_security_policy={
'default-src': "'self'",
'script-src': "'self' 'unsafe-inline'",
'style-src': "'self' 'unsafe-inline'",
'img-src': ["'self'", 'data:', 'https:'],
'font-src': "'self'",
'connect-src': "'self'",
'frame-ancestors': "'none'"
},
force_https=True,
strict_transport_security=True,
session_cookie_secure=True,
session_cookie_http_only=True,
session_cookie_samesite='Lax'
)
# Disable debug mode in production
app.config['DEBUG'] = False
app.config['TESTING'] = False
Database Security
# ============================================
# SECURE DATABASE CONFIGURATION
# ============================================
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# PostgreSQL with SSL
engine = create_engine(
os.getenv('DATABASE_URL'),
pool_size=10,
max_overflow=20,
pool_pre_ping=True, # Verify connections before use
connect_args={
'sslmode': 'require',
'options': '-c statement_timeout=30000' # 30s query timeout
}
)
# MySQL secure configuration
# ssl_args = {'ssl': {'ca': '/path/to/ca.pem'}}
# Database user with minimal privileges
"""
-- Create application user with minimal permissions
CREATE USER 'app_user'@'%' IDENTIFIED BY 'secure_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON app_db.* TO 'app_user'@'%';
-- Separate admin user
CREATE USER 'app_admin'@'%' IDENTIFIED BY 'different_password';
GRANT ALL PRIVILEGES ON app_db.* TO 'app_admin'@'%';
-- Read-only user for reports
CREATE USER 'app_reader'@'%' IDENTIFIED BY 'readonly_password';
GRANT SELECT ON app_db.* TO 'app_reader'@'%';
"""
Authentication & Authorization
JWT Implementation
# ============================================
# SECURE JWT AUTHENTICATION
# ============================================
import jwt
import time
from datetime import datetime, timedelta
from typing import Optional
class JWTAuth:
def __init__(self, secret_key: str, algorithm: str = 'HS256'):
self.secret = secret_key
self.algorithm = algorithm
self.access_token_expiry = 15 * 60 # 15 minutes
self.refresh_token_expiry = 7 * 24 * 60 * 60 # 7 days
def create_access_token(self, user_id: int, claims: dict = None) -> str:
"""Create short-lived access token"""
now = int(time.time())
payload = {
'sub': str(user_id),
'iat': now,
'exp': now + self.access_token_expiry,
'type': 'access',
**(claims or {})
}
return jwt.encode(payload, self.secret, algorithm=self.algorithm)
def create_refresh_token(self, user_id: int) -> str:
"""Create refresh token"""
now = int(time.time())
payload = {
'sub': str(user_id),
'iat': now,
'exp': now + self.refresh_token_expiry,
'type': 'refresh',
'jti': secrets.token_urlsafe(16) # Unique ID for revocation
}
return jwt.encode(payload, self.secret, algorithm=self.algorithm)
def verify_token(self, token: str, token_type: str = 'access') -> dict:
"""Verify and decode token"""
try:
payload = jwt.decode(
token,
self.secret,
algorithms=[self.algorithm]
)
if payload.get('type') != token_type:
raise ValueError('Invalid token type')
return payload
except jwt.ExpiredSignatureError:
raise ValueError('Token expired')
except jwt.InvalidTokenError:
raise ValueError('Invalid token')
def decode_without_verify(self, token: str) -> dict:
"""Decode without verification (for logging)"""
return jwt.decode(
token,
options={"verify_signature": False}
)
# Secure token storage
"""
1. Access Token:
- Store in memory (JavaScript)
- NEVER in localStorage (XSS vulnerable)
- Return in response body, store in memory variable
2. Refresh Token:
- HttpOnly cookie
- Secure flag (HTTPS only)
- SameSite=Lax or Strict
- Stored server-side with revocation list
3. Never store tokens in:
- localStorage
- sessionStorage
- URL parameters
- Browser history
"""
# Using refresh tokens securely
class RefreshTokenStore:
def __init__(self, redis_client):
self.redis = redis_client
def store(self, user_id: int, token_id: str, ttl: int = 604800):
"""Store refresh token with revocation capability"""
key = f"refresh_token:{token_id}"
self.redis.setex(key, ttl, str(user_id))
# Index tokens per user so they can all be revoked together
self.redis.sadd(f"user_refresh_tokens:{user_id}", token_id)
self.redis.expire(f"user_refresh_tokens:{user_id}", ttl)
def revoke(self, token_id: str):
"""Revoke a refresh token"""
self.redis.delete(f"refresh_token:{token_id}")
def revoke_all(self, user_id: int):
"""Revoke all refresh tokens for a user"""
index_key = f"user_refresh_tokens:{user_id}"
for token_id in self.redis.smembers(index_key):
token = token_id.decode() if isinstance(token_id, bytes) else token_id
self.redis.delete(f"refresh_token:{token}")
self.redis.delete(index_key)
def is_valid(self, token_id: str) -> bool:
"""Check if token is valid (not revoked)"""
return self.redis.exists(f"refresh_token:{token_id}")
OAuth 2.0 Implementation
# ============================================
# OAUTH 2.0 AUTHORIZATION CODE FLOW
# ============================================
class OAuth2Provider:
def __init__(self, client_id: str, client_secret: str, redirect_uri: str):
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
self.token_url = "https://oauth.provider.com/token"
self.auth_url = "https://oauth.provider.com/authorize"
def get_authorization_url(self, state: str, scopes: list) -> str:
"""Generate OAuth authorization URL"""
params = {
'client_id': self.client_id,
'redirect_uri': self.redirect_uri,
'response_type': 'code',
'scope': ' '.join(scopes),
'state': state # CSRF protection
}
return f"{self.auth_url}?{urllib.parse.urlencode(params)}"
def exchange_code_for_token(self, code: str) -> dict:
"""Exchange authorization code for tokens"""
response = requests.post(
self.token_url,
data={
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': self.redirect_uri,
'client_id': self.client_id,
'client_secret': self.client_secret
},
headers={'Accept': 'application/json'}
)
if response.status_code != 200:
raise ValueError("Token exchange failed")
return response.json()
# PKCE (Proof Key for Code Exchange) for public clients
class PKCEOAuth2Provider(OAuth2Provider):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.code_verifiers = {} # Store temporarily
def generate_pkce_pair(self) -> tuple:
"""Generate code verifier and challenge"""
code_verifier = secrets.token_urlsafe(64)
code_challenge = hashlib.sha256(
code_verifier.encode()
).digest()
code_challenge = base64.urlsafe_b64encode(code_challenge).decode()
code_challenge = code_challenge.replace('=', '')
return code_verifier, code_challenge
def get_authorization_url(self, state: str, scopes: list,
code_challenge: str) -> str:
"""Include PKCE in authorization URL"""
params = {
'client_id': self.client_id,
'redirect_uri': self.redirect_uri,
'response_type': 'code',
'scope': ' '.join(scopes),
'state': state,
'code_challenge': code_challenge,
'code_challenge_method': 'S256'
}
return f"{self.auth_url}?{urllib.parse.urlencode(params)}"
def exchange_code_for_token(self, code: str, code_verifier: str) -> dict:
"""Exchange with PKCE verification"""
response = requests.post(
self.token_url,
data={
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': self.redirect_uri,
'client_id': self.client_id,
# Public clients (SPAs, mobile apps) have no client_secret;
# the code_verifier proves this client started the flow.
'code_verifier': code_verifier
}
)
return response.json()
Secure Coding Practices
# ============================================
# INPUT VALIDATION
# ============================================
from pydantic import BaseModel, EmailStr, field_validator
from typing import Optional
import re
class UserInput(BaseModel):
email: EmailStr
username: str
age: int
website: Optional[str] = None
@field_validator('username')
@classmethod
def username_alphanumeric(cls, v):
if not re.match(r'^[a-zA-Z0-9_]{3,20}$', v):
raise ValueError('Username must be 3-20 alphanumeric characters')
return v
@field_validator('age')
@classmethod
def age_valid(cls, v):
if v < 0 or v > 150:
raise ValueError('Age must be between 0 and 150')
return v
@field_validator('website')
@classmethod
def website_valid(cls, v):
if v and not re.match(r'^https?://', v):
raise ValueError('Website must start with http:// or https://')
return v
# File upload validation
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf'}
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB
def validate_file(file):
"""Validate uploaded file"""
# Check extension
ext = file.filename.rsplit('.', 1)[1].lower()
if ext not in ALLOWED_EXTENSIONS:
raise ValueError(f'Extension {ext} not allowed')
# Check size
file.seek(0, 2) # Seek to end
size = file.tell()
file.seek(0) # Reset position
if size > MAX_FILE_SIZE:
raise ValueError(f'File size {size} exceeds limit')
# Check content type
if not file.content_type.startswith('image/'):
if file.content_type != 'application/pdf':
raise ValueError('Invalid file type')
return True
# ============================================
# OUTPUT ENCODING
# ============================================
import html
import bleach
def safe_html(user_input: str) -> str:
"""Sanitize HTML to prevent XSS"""
allowed_tags = ['b', 'i', 'u', 'em', 'strong', 'a', 'p', 'br']
allowed_attrs = {'a': ['href', 'title']}
return bleach.clean(
user_input,
tags=allowed_tags,
attributes=allowed_attrs,
strip=True
)
def escape_html(text: str) -> str:
"""Escape HTML entities"""
return html.escape(text, quote=True)
# ============================================
# SECURE SESSION MANAGEMENT
# ============================================
class SecureSession:
config = {
'SESSION_TYPE': 'redis',
'SESSION_PERMANENT': False,
'SESSION_USE_SIGNER': True,
'SESSION_KEY_PREFIX': 'session:',
'SESSION_COOKIE_NAME': '__Host-session',
'SESSION_COOKIE_HTTPONLY': True,
'SESSION_COOKIE_SECURE': True, # HTTPS only
'SESSION_COOKIE_SAMESITE': 'Lax',
'SESSION_COOKIE_DOMAIN': None,
'PERMANENT_SESSION_LIFETIME': 3600 # 1 hour
}
# ============================================
# RATE LIMITING
# ============================================
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(
key_func=get_remote_address,
default_limits=["200 per day", "50 per hour"],
storage_uri="redis://localhost:6379"
)
@app.route('/api/login', methods=['POST'])
@limiter.limit("5 per minute")
def login():
# Rate limited endpoint
pass
@app.route('/api/signup', methods=['POST'])
@limiter.limit("3 per hour")
def signup():
# Rate limited endpoint
pass
Interview Questions
Q1: What is the OWASP Top 10?
The OWASP Top 10 is a standard awareness document for developers about the most critical security risks to web applications. The current web edition (2021) includes: Broken Access Control, Cryptographic Failures, Injection, Insecure Design, Security Misconfiguration, Vulnerable Components, Authentication Failures, Software Integrity Failures, Logging Failures, and SSRF.
Q2: How do you prevent SQL injection?
Use parameterized queries or prepared statements. Never concatenate user input into SQL strings. Use ORM frameworks that handle parameterization automatically.
Q3: What is XSS and how do you prevent it?
Cross-Site Scripting (XSS) injects malicious scripts into web pages. Prevention: output encoding, Content Security Policy headers, input validation, and sanitizing user-generated content.
Q4: What's the difference between authentication and authorization?
- Authentication: Verifies who you are (login credentials, MFA)
- Authorization: Determines what you can access (permissions, roles)
Q5: How do you securely store passwords?
Use adaptive hashing algorithms like bcrypt, Argon2, or PBKDF2 with a high work factor. Never use MD5, SHA1, or other fast hashes for passwords.
Q6: What is SSRF and how do you prevent it?
Server-Side Request Forgery (SSRF) lets an attacker make the server send requests to internal resources it shouldn't reach. Prevention: validate and allowlist URLs, block private IP ranges (127.x, 10.x, 169.254.x), use egress firewalls, avoid passing raw URLs to fetch functions.
Q7: What is SBOM and why does it matter for security?
A Software Bill of Materials (SBOM) is a machine-readable inventory of every dependency and its version in your application. It matters because it lets you quickly find which systems are affected when a CVE is disclosed, instead of manually grepping dependency files.
Q8: What is Zero Trust architecture?
Zero Trust means "never trust, always verify" — no implicit trust based on network location. Every request is authenticated and authorized individually, often using mTLS, short-lived credentials, and continuous monitoring rather than broad network perimeter rules.
Q9: What are common JWT security mistakes?
Common mistakes: storing secrets in code, using weak signing algorithms (none/HS256 with guessable secret), not setting expiry, putting sensitive data in the payload (it is only base64, not encrypted), and not validating issuer/audience.
Q10: What is the OWASP Top 10 for LLM applications?
The OWASP Top 10 for LLM Applications (2025 edition) covers AI-specific threats: prompt injection, sensitive information disclosure, supply chain, data and model poisoning, improper output handling, excessive agency, system prompt leakage, vector and embedding weaknesses, misinformation, and unbounded consumption.
Q11: How do you secure API endpoints?
Use authentication on every endpoint, apply rate limiting, validate and sanitize input, set least-privilege scopes, enforce HTTPS, add CORS allowlists, and log access. Also add request signing for server-to-server APIs.
Q12: What is a Content Security Policy (CSP)?
CSP is an HTTP header that tells the browser which sources of scripts, styles, and images are allowed. It blocks injected scripts (XSS) by refusing to execute content from non-allowlisted origins.
Q13: How do you protect against dependency supply-chain attacks?
Pin exact versions, use lockfiles, verify checksums, sign packages, scan with tools like Dependabot/Trivy, monitor CVEs, and consider private registries mirroring vetted packages (proxying, not bypassing, upstream).
Q14: What is the difference between encryption in transit and at rest?
In transit: data encrypted while moving (TLS/HTTPS). At rest: data encrypted while stored (disk encryption, database encryption, S3 SSE). Both are required; neither substitutes for the other.
Q15: How do you detect security incidents in production?
Collect and alert on: failed login spikes, unusual IAM/role usage, outbound egress anomalies, API error anomalies, and audit-log tampering. Centralize logs (SIEM), set alerts on known-bad patterns, and retain immutable audit trails.
Q16: What is rate limiting and which algorithms exist?
Rate limiting caps requests per client over a window. Common algorithms: token bucket, leaky bucket, fixed window, and sliding window log/counter. It protects APIs from abuse, brute force, and DDoS.
Q17: How does mTLS work and when is it used?
Mutual TLS: both client and server present certificates and verify each other. Used in zero-trust networks, service meshes (Istio/Linkerd), and internal service-to-service APIs where both parties need strong identity.
Q18: What is the principle of least privilege?
Give every user, role, and service only the permissions required to do its job, nothing more. Applied to IAM roles, database grants, filesystem ACLs, and API scopes. Limits the blast radius if a credential is compromised.
Q19: How do you handle secrets rotation safely?
Store secrets in a secrets manager (Vault, AWS Secrets Manager), never in code or env files committed to git. Rotate on a schedule or on compromise: generate new value, deploy, verify, then deactivate old value. Use temporary/STS credentials where possible.
Q20: What are common misconfigurations in cloud security?
Public S3 buckets, overly permissive IAM policies, open security groups (0.0.0.0/0), disabled logging, unencrypted storage, exposed debug endpoints, and root credentials used for automation instead of limited roles.
Q21: What is a WAF and what does it protect against?
A Web Application Firewall filters HTTP traffic between clients and your app, blocking known attack patterns — SQLi, XSS, path traversal, bot traffic. It is a first line of defense, not a replacement for secure code.
Q22: How do you safely handle file uploads?
Validate file type by content (not just extension), limit size, scan with antivirus, store outside the web root, serve with Content-Disposition and a random filename, and never execute uploaded files.
Q23: What is the principle of defense in depth?
Layer multiple independent security controls so that if one fails, another still catches the attack: WAF + input validation + parameterized queries + least privilege + monitoring + encryption.
Q24: How do you test for security vulnerabilities in your codebase?
SAST (static analysis, e.g., Semgrep, Bandit) scans source; DAST (dynamic, e.g., ZAP) scans running apps; dependency scanners (Trivy) check packages; secret scanners (gitleaks) check repos; penetration tests probe real-world access paths.
Q25: What is a session fixation attack?
An attacker sets or forces a victim's session ID, then later hijacks it after login. Prevention: regenerate session ID on login, use HttpOnly/Cookie flags, expire sessions, and bind sessions to other signals.
Q26: What is open redirect?
An endpoint that takes a ?next= or ?redirect= parameter and redirects unvalidated. Attackers use it for phishing by disguising a trusted domain. Fix: validate redirect targets against an allowlist of internal paths.
Q27: How do you secure a CI/CD pipeline?
Lock down pipeline execution, never store secrets in pipeline config (use vault integration), pin runner images, verify artifact signatures, restrict merge permissions, and review third-party actions before use.
Q28: What is container image scanning?
Automated scanning of container images for vulnerable OS packages and known CVEs before deployment (Trivy, Grype, Snyk). Should run in CI and block promotion to production when critical vulnerabilities are found.
Q29: What is homomorphic encryption used for?
It allows computation on encrypted data without decrypting it first. Useful in healthcare and finance for privacy-preserving analytics. Still expensive (high compute overhead) so rarely used at scale in production yet.
Q30: What is the difference between symmetric and asymmetric encryption?
Symmetric: same key encrypts and decrypts (AES), fast, used for bulk data. Asymmetric: public/private key pair (RSA, ECC), slower, used for key exchange and digital signatures. Production systems combine both (hybrid, e.g., TLS).
Senior / Principal — Real World Security Scenarios
Q31: Secrets leaked in Git history
Level: Senior
Scenario: A developer committed an .env file with AWS keys and database password to Git. The push succeeded. The keys are now in Git history even after the file was removed in a later commit.
Impact: Cloud account compromise. Database breach. Incident response required. Key rotation needed.
Root Cause: Secrets committed to version control. No pre-commit hook or secret scanning. .env not in .gitignore.
Simple explanation: You wrote your house key code on a postcard and mailed it to everyone. Even if you tear up your copy, others still have it.
Technical Answer:
- Add
.env,*.secret,*.pemto.gitignoreimmediately. - Remove from history:
git filter-repoor BFG Repo-Cleaner (notfilter-branch). - Rotate all exposed keys/passwords immediately (assume compromise).
- Use pre-commit hooks (
detect-secrets,truffleHog) to block secrets before commit. - Use a secret manager (AWS Secrets Manager, Vault, Doppler) instead of
.envin repo.
Code/Syntax Justification:
# Remove secrets from history
git filter-repo --path .env --invert-paths
# Force push (coordinate with team)
git push --force
# Rotate: revoke old AWS keys, generate new
Workflow Diagram:
Secret committed
|
v
Detected (pre-commit hook or audit)
|
v
Remove from history (filter-repo/BFG)
|
v
Rotate all exposed credentials
|
v
Pre-commit hook blocks future commits
🔍 Behind the Question: Secret scanning, git history rewriting, key rotation, pre-commit hooks.
❌ The Red Flags: .env in repo; no pre-commit secret scanning; not rotating after leak.
Q32: Broken access control — IDOR vulnerability
Level: Principal
Scenario: An API endpoint GET /api/users/{id}/profile returns any user's profile when you change the id in the URL. No check that the requesting user owns the profile or is an admin.
Impact: Unauthorized data exposure. Privacy violation. Compliance breach (GDPR, HIPAA).
Root Cause: Insecure Direct Object Reference (IDOR). Authorization check missing at the object level. Authentication (who you are) ≠ Authorization (what you can access).
Simple explanation: A hotel room key opens every room because the lock doesn't check who you are, just that you have a key.
Technical Answer:
- Enforce object-level authorization:
if obj.owner != current_user and not current_user.is_admin: raise 403. - Use middleware/decorator for authorization on every endpoint.
- Test with different user roles (authorized, unauthorized, admin).
- Use UUIDs instead of sequential IDs to reduce enumeration (defense in depth).
- Log authorization failures for detection.
Code/Syntax Justification:
# FastAPI dependency
async def check_ownership(user_id: int, current_user: User = Depends(get_current_user)):
if current_user.id != user_id and not current_user.is_admin:
raise HTTPException(status_code=403, detail="Not authorized")
return user_id
@app.get("/users/{user_id}/profile")
async def get_profile(user_id: int = Depends(check_ownership)):
...
Workflow Diagram:
Request: GET /api/users/42/profile (current user = 1)
|
v
Authentication: user 1 is valid
|
v
Authorization: does user 1 own user 42? NO. Is admin? NO.
|
v
Return 403 Forbidden
🔍 Behind the Question: IDOR, object-level authorization, authentication vs authorization, UUIDs.
❌ The Red Flags: No authorization check; relying on URL obscurity; sequential IDs guessable.
Insecure Design and Threat Modelling
Q33: What is "Insecure Design" in the OWASP Top 10, and how is it different from an implementation bug?
Insecure Design (A04 in the 2021 list) covers flaws in the design itself: a control that was never planned, so no amount of perfect coding would make the feature safe. An implementation bug is a correct design coded wrongly.
| Implementation bug | Insecure design | |
|---|---|---|
| Example | SQL built with an f-string in one query | Password reset by "security questions" whose answers are on social media |
| Example | Missing @login_required on one route | A "transfer money" API with no limits, no step-up auth, and no fraud checks |
| Example | Off-by-one in a rate limiter | No rate limit was designed for an SMS-sending endpoint, so attackers run up the SMS bill |
| Fix | Patch the code | Redesign the feature: add a control, change the flow |
Typical insecure-design patterns in backend systems:
- Trusting the client for price, role, discount, or "is this step done?" state.
- No limits on business flows: unlimited coupon attempts, gift-card balance checks, or account creations.
- Single-step sensitive actions: changing email and password in one request with no re-authentication.
- Race-prone business logic: check-then-act on balances or single-use items (Q35).
- Missing tenant isolation as a design principle, leaving every query to remember
tenant_id(Q53).
How you prevent it: threat model new features (Q34), use secure design patterns and reference architectures, write abuse cases next to user stories ("as an attacker I want to redeem one coupon 100 times"), and test those abuse cases.
Q34: What is threat modelling, and how do you apply STRIDE to a feature?
Threat modelling is a structured way to answer four questions before (and while) you build:
- What are we building? Draw a data-flow diagram (DFD) with trust boundaries.
- What can go wrong? Use a framework such as STRIDE to enumerate threats.
- What are we going to do about it? Mitigate, accept, transfer or eliminate each threat.
- Did we do a good job? Review, test, and revisit when the design changes.
STRIDE maps each threat category to the security property it violates:
| Threat | Violates | Typical mitigation |
|---|---|---|
| Spoofing | Authentication | Strong auth, MFA, mTLS between services |
| Tampering | Integrity | Signatures/HMAC, input validation, immutable storage |
| Repudiation | Non-repudiation | Tamper-evident audit logs with actor, action, time |
| Information disclosure | Confidentiality | Authorization checks, encryption, minimal responses |
| Denial of service | Availability | Rate limits, quotas, timeouts, size limits |
| Elevation of privilege | Authorization | Least privilege, deny-by-default, server-side checks |
Worked example: a new "export invoices as PDF" feature.
[Browser] --HTTPS--> [API gateway] ==trust boundary==> [Export API] --> [Queue] --> [PDF worker] --> [S3 bucket]
| |
[Postgres] signed URL --> [Browser]
S: Can someone call the Export API as another user? -> require auth; derive user from token, not a parameter
T: Can the job message on the queue be modified? -> queue IAM: only Export API may publish; validate in worker
R: Can a user deny requesting an export of all invoices? -> audit log: user, tenant, filters, time
I: Can user A download user B's PDF? -> object keys include tenant; short-lived signed URLs
Does the PDF renderer fetch remote URLs (SSRF)? -> disable remote resources in the renderer
D: Can one user request 10,000 exports? -> per-tenant quota, max date range, job concurrency cap
E: Does the worker run with broad S3 permissions? -> worker role may only write to exports/ prefix
Interview tips: keep it lightweight and repeatable (30–60 minutes per significant feature, a template in the design doc), focus on trust boundaries because that is where most threats live, and record decisions so the model is updated when the design changes. Other frameworks you can mention: PASTA (risk-centric), LINDDUN (privacy threats), and attack trees.
Q35: How do you prevent race conditions in business logic, such as a single-use coupon being redeemed twice?
The classic flaw is check-then-act (also called TOCTOU, time-of-check to time-of-use): read state, decide, then write, as separate steps. Two concurrent requests both pass the check before either writes. Attackers trigger this on purpose by sending many parallel requests (sometimes called a "limit overrun" attack) against coupons, gift-card balances, withdrawals, likes or votes.
Fixes, from strongest to weakest:
- Let the database enforce the invariant: a unique constraint (one redemption row per coupon), or a single atomic conditional
UPDATE ... WHERE <still valid>whose row count tells you whether you won. - Lock the row for the duration of the decision:
SELECT ... FOR UPDATEinside a transaction (PostgreSQL, MySQL InnoDB). - Serializable isolation with retry on serialization failure.
- Idempotency keys for client retries, so the same request processed twice has one effect.
Application-level locks (a Python threading.Lock) do not work across multiple processes or servers.
import sqlite3
import threading
DB = "coupons.db"
def setup() -> None:
with sqlite3.connect(DB) as conn:
conn.execute("DROP TABLE IF EXISTS coupons")
conn.execute("CREATE TABLE coupons (code TEXT PRIMARY KEY, redeemed_by TEXT)")
conn.execute("INSERT INTO coupons VALUES ('WELCOME50', NULL)")
# VULNERABLE: check-then-act. Two concurrent requests can both pass the SELECT
# before either UPDATE runs, so the single-use coupon is redeemed twice.
def redeem_vulnerable(conn: sqlite3.Connection, code: str, user_id: str) -> bool:
row = conn.execute("SELECT redeemed_by FROM coupons WHERE code = ?", (code,)).fetchone()
if row is None or row[0] is not None:
return False
conn.execute("UPDATE coupons SET redeemed_by = ? WHERE code = ?", (user_id, code))
conn.commit()
return True
# SAFE: one atomic conditional UPDATE. The database guarantees only one
# statement can flip redeemed_by from NULL, so rowcount tells us who won.
def redeem_safe(conn: sqlite3.Connection, code: str, user_id: str) -> bool:
cur = conn.execute(
"UPDATE coupons SET redeemed_by = ? WHERE code = ? AND redeemed_by IS NULL",
(user_id, code),
)
conn.commit()
return cur.rowcount == 1
def attempt(user_id: str, results: list[bool]) -> None:
conn = sqlite3.connect(DB, timeout=5)
results.append(redeem_safe(conn, "WELCOME50", user_id))
conn.close()
setup()
results: list[bool] = []
threads = [threading.Thread(target=attempt, args=(f"user-{i}", results)) for i in range(20)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"successful redemptions: {results.count(True)} of {len(results)}") # 1 of 20
For balances, apply the same idea: UPDATE accounts SET balance = balance - :amount WHERE id = :id AND balance >= :amount, and treat "0 rows updated" as insufficient funds. Test these flows with concurrent requests in your test suite. A sequential test will never find a race.
Vulnerable and Outdated Components
Q36: Your scanner reports 140 vulnerable dependencies. How do you triage and fix them?
"Vulnerable and Outdated Components" (A06 in the 2021 list) is about running libraries, frameworks, runtimes and base images with known vulnerabilities. The hard part is not finding them; it is deciding what to fix first and making fixes routine.
1. Know exactly what you run. Lock every dependency, including transitive ones, with hashes, and generate an SBOM for each build.
# Pin direct + transitive dependencies with hashes (pip-tools or uv)
pip-compile --generate-hashes requirements.in -o requirements.txt
# or
uv pip compile --generate-hashes requirements.in -o requirements.txt
# Install refusing anything that is not pinned and hash-matched
pip install --require-hashes -r requirements.txt
# Audit against known-vulnerability databases (exit code is non-zero when issues are found)
pip-audit -r requirements.txt
# Who pulls in this transitive package?
pipdeptree --reverse --packages urllib3
2. Prioritise by real risk, not raw CVSS:
| Factor | Question |
|---|---|
| Exploitability | Is it being exploited in the wild (for example, listed in CISA's Known Exploited Vulnerabilities catalogue)? What is its EPSS score? |
| Reachability | Does our code actually call the vulnerable function, with attacker-controlled input? |
| Exposure | Internet-facing service, or an internal batch job? |
| Impact | Remote code execution versus a minor information leak |
| Environment | Is it a runtime dependency, or only a dev/test tool that never ships? |
3. Fix in the cheapest safe way: upgrade the direct dependency that pulls it in; if that is not possible, pin the transitive package with a constraints file; if no fix exists yet, apply a compensating control (disable the feature, WAF rule) and record a time-bounded exception.
4. Make it continuous: automated update PRs (Dependabot or Renovate) with good tests so merging is cheap, pip-audit in CI that fails builds on new high-severity issues, and base-image rebuilds on a schedule even when your code did not change.
A strong answer also mentions VEX (Vulnerability Exploitability eXchange) statements: a machine-readable "this CVE is not exploitable in our product because ..." that stops the same false positive being re-triaged every week.
Q37: What are dependency confusion and typosquatting, and how do you protect a Python build from them?
- Typosquatting: an attacker publishes a malicious package with a name close to a popular one (
reqeusts,python-dateutils), hoping someone mistypes it. Malicious code often runs at install time from the package's build step, or at import. - Dependency confusion: your company uses an internal package, for example
acme-billing-client, from a private index. An attacker publishesacme-billing-clientwith a higher version number on the public index. If your installer looks at both indexes and picks the highest version, it installs the attacker's package inside your CI, with CI's secrets.
The common Python mistake is --extra-index-url. pip treats every configured index as equal and chooses the best version across all of them; it does not prefer the "extra" one.
# pip.conf - VULNERABLE to dependency confusion:
# pip considers both PyPI and the internal index and may pick a higher public version
[global]
extra-index-url = https://pypi.internal.example.com/simple
# pip.conf - SAFER: exactly one index, an internal proxy that serves internal packages
# from the private repository and proxies vetted public packages from PyPI
[global]
index-url = https://pypi.internal.example.com/simple
Defences:
- One index (a repository manager that proxies the public index), or an installer setting that pins each package to one index. uv, for example, by default stops at the first index that has a package rather than merging versions across indexes.
- Hash-pinned lockfiles (
--require-hashes): even a same-named, same-version package from elsewhere fails the hash check. - Reserve your internal names on the public index (an empty placeholder package), or use a namespace prefix you control.
- Review new dependencies: who maintains it, how old it is, download counts, and whether the name is suspiciously close to a popular package.
- Least privilege in CI: builds that install dependencies should not have production deploy credentials in the same job.
API Security and Data Access
Q38: What is the OWASP API Security Top 10, and how does it differ from the web Top 10?
APIs expose data and business logic directly, often to clients you do not control, so their most common failures are about authorization and abuse rather than browser-side issues. The 2023 edition of the OWASP API Security Top 10:
| ID | Risk | One-line meaning |
|---|---|---|
| API1 | Broken Object Level Authorization (BOLA) | Changing /orders/123 to /orders/124 returns someone else's order (also called IDOR) |
| API2 | Broken Authentication | Weak login, token validation or credential-recovery flows |
| API3 | Broken Object Property Level Authorization | Reading fields you should not see (excessive data exposure) or writing fields you should not set (mass assignment) |
| API4 | Unrestricted Resource Consumption | No limits on request size, page size, uploads, expensive queries, or paid third-party calls (SMS, email) |
| API5 | Broken Function Level Authorization (BFLA) | A regular user can call admin functions |
| API6 | Unrestricted Access to Sensitive Business Flows | Bots automating ticket buying, sign-up bonuses, or comment spam at scale |
| API7 | Server Side Request Forgery (SSRF) | The API fetches a URL supplied by the user and reaches internal systems |
| API8 | Security Misconfiguration | Verbose errors, permissive CORS, missing TLS, default credentials |
| API9 | Improper Inventory Management | Old API versions, debug endpoints and undocumented hosts still running unprotected |
| API10 | Unsafe Consumption of APIs | Trusting data from third-party APIs more than user input |
Differences from the web Top 10 worth stating in an interview:
- Authorization appears three times (object, property, function). For APIs, "is this caller allowed to do this to this object and this field?" is the central question.
- Business-flow abuse and resource consumption are first-class risks, because APIs make automation trivial.
- Inventory is a risk on its own: you cannot protect an endpoint you forgot exists (Q60).
- Classic injection is not a separate entry; it is covered by the general Top 10 and still applies.
Q39: What is mass assignment (Broken Object Property Level Authorization), and how do you prevent it in Python?
API3 has two halves:
- Mass assignment (write side): the server binds every field in the request body to the model, so a client can set fields it should never control:
is_admin,plan,balance,email_verified,tenant_id. - Excessive data exposure (read side): the server serialises the whole model, and the client receives
password_hash, internal flags or other users' emails. The front end "just doesn't display them", but an attacker reads the raw JSON.
The fix for both is explicit input and output schemas per operation. Never bind a request directly to an ORM model, and never return an ORM model directly.
from dataclasses import dataclass
from pydantic import BaseModel, ConfigDict, Field, ValidationError
@dataclass
class User: # stands in for an ORM model
id: int
email: str
display_name: str
bio: str | None = None
is_admin: bool = False
plan: str = "free"
password_hash: str = "argon2id$..."
# VULNERABLE: copies every key the client sends onto the model.
def update_profile_vulnerable(user: User, body: dict) -> None:
for key, value in body.items():
setattr(user, key, value) # {"is_admin": true, "plan": "enterprise"} just works
# SAFE: an explicit input model that lists only client-writable fields...
class ProfileUpdateIn(BaseModel):
model_config = ConfigDict(extra="forbid") # unknown fields are rejected, not ignored
display_name: str | None = Field(default=None, min_length=1, max_length=50)
bio: str | None = Field(default=None, max_length=500)
# ...and an explicit output model that lists only fields the client may see.
class ProfileOut(BaseModel):
id: int
display_name: str
bio: str | None
def update_profile(user: User, body: dict) -> ProfileOut:
changes = ProfileUpdateIn.model_validate(body)
for field, value in changes.model_dump(exclude_unset=True).items():
setattr(user, field, value)
return ProfileOut.model_validate(user, from_attributes=True)
alice = User(id=1, email="alice@example.com", display_name="Alice")
print(update_profile(alice, {"bio": "Backend engineer"}))
# id=1 display_name='Alice' bio='Backend engineer' (no email, no is_admin, no password_hash)
try:
update_profile(alice, {"display_name": "Mallory", "is_admin": True})
except ValidationError as exc:
print(exc.errors()[0]["type"], exc.errors()[0]["loc"]) # extra_forbidden ('is_admin',)
print(alice.is_admin) # False
In FastAPI, the same idea is expressed with a request model in the function signature and response_model=ProfileOut on the route. In Django REST Framework, use explicit fields (never fields = "__all__") and read_only_fields. Rejecting unknown fields (extra="forbid") is better than silently ignoring them, because the rejection also shows up in logs when someone probes your API.
When different roles may write different fields (an admin may change plan, a user may not), use separate schemas per role, not one schema with if statements scattered through the handler.
Q40: What is Broken Function Level Authorization, and how do you make sure no admin endpoint is ever left unprotected?
BFLA (API5) means a caller can invoke a function they should not have access to, usually an admin or internal operation: DELETE /api/users/7, POST /api/admin/refunds, GET /api/internal/export. Common causes:
- Admin endpoints live next to user endpoints, and each one must remember its own decorator.
- The UI hides the admin button, so the team assumed nobody would call the endpoint.
- Changing the HTTP method bypasses the check (
GETis protected,PUTon the same path is not). - "Internal" endpoints assume the network is trusted.
Design so that forgetting is impossible: deny by default and attach authorization to the router, not to each endpoint.
from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException, status
from fastapi.testclient import TestClient
# DEMO ONLY: real apps derive the user from a verified session or token, never from a plain header.
FAKE_USERS = {"token-alice": {"id": 1, "roles": {"user"}}, "token-root": {"id": 2, "roles": {"user", "admin"}}}
def current_user(authorization: str = Header(...)) -> dict:
user = FAKE_USERS.get(authorization.removeprefix("Bearer "))
if user is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED)
return user
def require_role(role: str):
def checker(user: dict = Depends(current_user)) -> dict:
if role not in user["roles"]:
raise HTTPException(status.HTTP_403_FORBIDDEN)
return user
return checker
# Every route on this router inherits the admin check: nobody can forget it per endpoint.
admin = APIRouter(prefix="/admin", dependencies=[Depends(require_role("admin"))])
@admin.delete("/users/{user_id}", status_code=204)
def delete_user(user_id: int) -> None:
...
@admin.get("/reports/revenue")
def revenue_report() -> dict:
return {"total": 1_234_567}
app = FastAPI()
app.include_router(admin)
client = TestClient(app)
print(client.get("/admin/reports/revenue", headers={"Authorization": "Bearer token-alice"}).status_code) # 403
print(client.get("/admin/reports/revenue", headers={"Authorization": "Bearer token-root"}).status_code) # 200
print(client.delete("/admin/users/7", headers={"Authorization": "Bearer token-alice"}).status_code) # 403
Additional layers:
- Separate deployment for admin APIs (different host, network policy, SSO with MFA), so a public-facing bug cannot reach them.
- An automated test that walks every registered route and asserts it has an auth dependency, failing CI when someone adds an unprotected endpoint (see Q60).
- Permission-based checks (
refunds:create) rather than role names sprinkled through code, so roles can change without touching handlers. - Log and alert on 403s for admin routes: a burst of them is someone probing.
Q41: "We use an ORM, so we're safe from SQL injection." Is that true?
Mostly, but not completely. ORMs parameterise values in their query builders. Injection comes back whenever user input becomes part of the SQL text itself:
- Raw SQL built with f-strings or
%, even when wrapped in SQLAlchemy'stext().text()does not sanitise anything; only bound parameters do. - Identifiers cannot be bound parameters: column names in
ORDER BY, table names,ASC/DESC. They need an allowlist. - Escape hatches: Django's
.raw()and.extra()andRawSQLwith string formatting; SQLAlchemy'sliteral_column()ortext()fragments insideorder_byorwherebuilt from input. LIKEpatterns: binding the value prevents injection, but%and_from the user still act as wildcards unless escaped. That is usually a correctness or performance issue (a user searching%scans everything), not injection.
from sqlalchemy import String, create_engine, select, text
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
class Base(DeclarativeBase):
pass
class Product(Base):
__tablename__ = "products"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
price: Mapped[int]
owner_id: Mapped[int]
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as s:
s.add_all(
[
Product(name="Red_Mug", price=12, owner_id=1),
Product(name="RedHat", price=20, owner_id=1),
Product(name="Secret", price=99, owner_id=2),
]
)
s.commit()
SORTABLE_COLUMNS = {"name": Product.name, "price": Product.price}
# VULNERABLE: user input interpolated into raw SQL fragments.
# term = "x' OR owner_id = 2 --" returns another owner's rows.
def search_vulnerable(session: Session, owner_id: int, term: str, sort: str):
sql = f"SELECT * FROM products WHERE owner_id = {owner_id} AND name LIKE '%{term}%' ORDER BY {sort}"
return session.execute(text(sql)).all() # text() does NOT make an f-string safe
def escape_like(term: str) -> str:
return term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
# SAFE: values are bound parameters; identifiers come from an allowlist.
def search_safe(session: Session, owner_id: int, term: str, sort: str) -> list[Product]:
order_column = SORTABLE_COLUMNS.get(sort, Product.name)
stmt = (
select(Product)
.where(Product.owner_id == owner_id)
.where(Product.name.like(f"%{escape_like(term)}%", escape="\\"))
.order_by(order_column)
)
return list(session.scalars(stmt))
# SAFE raw SQL, when you really need it: named bind parameters.
def total_value(session: Session, owner_id: int) -> int:
return session.execute(
text("SELECT COALESCE(SUM(price), 0) FROM products WHERE owner_id = :owner_id"),
{"owner_id": owner_id},
).scalar_one()
with Session(engine) as session:
print([p.name for p in search_safe(session, 1, "Red_", "price")]) # ['Red_Mug'] - "_" is literal
print([p.name for p in search_safe(session, 1, "' OR '1'='1", "name; DROP TABLE products")]) # []
print(total_value(session, 1)) # 32
Defence in depth beyond the code: the application's database user should have only the privileges it needs (no DDL, no access to other schemas), and a SAST rule (Semgrep or Bandit) can flag text(f"...") and .raw(f"...") patterns in review.
Tokens, OAuth and Browser Security
Q42: How do you validate a JWT safely? Explain the alg: none and algorithm-confusion attacks.
A JWT is header.payload.signature, each part base64url-encoded. The header names the signing algorithm. Two famous attacks abuse the fact that the token tells the verifier how to verify it:
alg: none: the attacker edits the payload, sets"alg": "none"and removes the signature. A naive library or verifier that honours the header accepts an unsigned token.- Algorithm confusion (key confusion): the server expects RS256 (asymmetric) and verifies with the RSA public key. The attacker creates a token with
"alg": "HS256"and signs it with HMAC, using that public key (which is public) as the HMAC secret. A verifier that passes "the key" plus "whatever algorithm the header says" to a generic verify function accepts it.
Both are prevented by the same rule: the server decides the algorithm, never the token. Then validate every claim that gives the token meaning:
| Check | Why |
|---|---|
| Signature with a pinned algorithm list | Blocks none and algorithm confusion |
exp (and nbf) with small leeway | Stolen tokens stop working |
iss | Token was minted by your identity provider, not another tenant of the same provider |
aud | Token was meant for this API. Without it, a token for service A works on service B |
kid from a trusted JWKS only | Never fetch keys from a URL inside the token (jku, x5u) |
| Token type / scope | An ID token or refresh token must not be accepted as an access token |
import base64
import json
import time
import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
ISSUER = "https://auth.example.com/"
AUDIENCE = "orders-api"
# In production the verifier fetches public keys from the issuer's JWKS endpoint:
# jwks = jwt.PyJWKClient("https://auth.example.com/.well-known/jwks.json")
# key = jwks.get_signing_key_from_jwt(token).key
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_pem = private_key.public_key().public_bytes(
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
)
def verify_access_token(token: str) -> dict:
return jwt.decode(
token,
key=public_pem,
algorithms=["RS256"], # pin the algorithm: never read it from the token
audience=AUDIENCE, # token must be meant for THIS API
issuer=ISSUER, # and minted by OUR identity provider
leeway=30, # small clock-skew allowance, in seconds
options={"require": ["exp", "iat", "iss", "aud", "sub"]},
)
now = int(time.time())
claims = {"sub": "user-42", "iss": ISSUER, "aud": AUDIENCE, "iat": now, "exp": now + 300}
good = jwt.encode(claims, private_key, algorithm="RS256")
print(verify_access_token(good)["sub"]) # user-42
wrong_audience = jwt.encode({**claims, "aud": "billing-api"}, private_key, algorithm="RS256")
expired = jwt.encode({**claims, "iat": now - 600, "exp": now - 300}, private_key, algorithm="RS256")
def b64url(data: dict) -> str:
return base64.urlsafe_b64encode(json.dumps(data).encode()).rstrip(b"=").decode()
unsigned = f"{b64url({'alg': 'none', 'typ': 'JWT'})}.{b64url(claims)}." # textbook "alg: none" token
for name, token in [("wrong audience", wrong_audience), ("expired", expired), ("alg none", unsigned)]:
try:
verify_access_token(token)
except jwt.InvalidTokenError as exc:
print(f"{name}: rejected ({type(exc).__name__})")
# wrong audience: rejected (InvalidAudienceError)
# expired: rejected (ExpiredSignatureError)
# alg none: rejected (InvalidAlgorithmError)
Other points interviewers like: HS256 is fine for a single service that both issues and verifies, but its secret must be long and random (not a dictionary word, which can be brute-forced offline from any captured token). Use asymmetric algorithms (RS256, ES256, EdDSA) whenever different parties issue and verify. And remember the payload is only encoded, not encrypted: anyone holding the token can read it.
Q43: JWTs are stateless. How do you implement logout and revocation?
You cannot "delete" a self-contained token that has already been issued; it stays valid until it expires. Practical designs combine several techniques:
- Short-lived access tokens (5–15 minutes). Revocation then means "stop issuing new ones", and the worst-case exposure is one token lifetime.
- Refresh tokens stored server-side (or at least tracked server-side), so they can be revoked: on logout, password change, or admin action.
- Refresh-token rotation with reuse detection. Each refresh returns a new refresh token and invalidates the old one. If an old token is ever presented again, someone has a copy, so revoke the whole token family.
- For immediate revocation of access tokens, check a small denylist of revoked
jtivalues (kept only until each token'sexp), or a per-user "token version" claim compared with the current version in the user record. Both reintroduce a lookup, which is fine for sensitive operations. - Opaque tokens with introspection (RFC 7662) are the alternative when instant revocation matters more than avoiding a network call.
import hashlib
import secrets
import time
from dataclasses import dataclass
@dataclass
class RefreshRecord:
user_id: str
family_id: str # all tokens descended from one login share a family
expires_at: float
used: bool = False
class RefreshTokenService:
"""In-memory sketch; production uses a database or Redis with atomic updates."""
def __init__(self, ttl_seconds: int = 14 * 24 * 3600) -> None:
self._records: dict[str, RefreshRecord] = {} # keyed by SHA-256 of the token
self._revoked_families: set[str] = set()
self._ttl = ttl_seconds
@staticmethod
def _digest(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest() # never store the raw token
def issue(self, user_id: str, family_id: str | None = None) -> str:
token = secrets.token_urlsafe(32)
self._records[self._digest(token)] = RefreshRecord(
user_id=user_id,
family_id=family_id or secrets.token_hex(16),
expires_at=time.time() + self._ttl,
)
return token
def rotate(self, token: str) -> str:
record = self._records.get(self._digest(token))
if record is None or record.expires_at < time.time() or record.family_id in self._revoked_families:
raise PermissionError("invalid refresh token")
if record.used:
# An already-rotated token came back: either the user or an attacker holds a stolen copy.
# We cannot tell which, so revoke the whole family and force a fresh login.
self._revoked_families.add(record.family_id)
raise PermissionError("refresh token reuse detected; all sessions in this family revoked")
record.used = True
return self.issue(record.user_id, record.family_id)
def revoke_user(self, user_id: str) -> None:
"""Logout everywhere / password change."""
for record in self._records.values():
if record.user_id == user_id:
self._revoked_families.add(record.family_id)
service = RefreshTokenService()
t1 = service.issue("user-42")
t2 = service.rotate(t1) # normal refresh: t1 is now spent
try:
service.rotate(t1) # attacker replays the stolen t1
except PermissionError as exc:
print(exc) # refresh token reuse detected; all sessions in this family revoked
try:
service.rotate(t2) # the legitimate client's token is now dead too
except PermissionError as exc:
print(exc) # invalid refresh token
A production detail worth raising: two legitimate tabs refreshing at the same moment can look like reuse. Teams usually allow a few seconds of grace during which the previous token returns the same successor, and they implement rotate atomically (a conditional update on used = false) so concurrent requests cannot both succeed.
Q44: Which OAuth 2.x / OpenID Connect flow should each kind of client use, and what does PKCE protect against?
OAuth 2.0 is about delegated authorization (getting an access token for an API). OpenID Connect (OIDC) adds authentication on top: an ID token that tells the client who logged in.
| Client | Recommended flow |
|---|---|
| Server-side web app (can keep a secret) | Authorization Code + PKCE |
| Single-page app | Authorization Code + PKCE; better still a Backend-for-Frontend (BFF) that keeps tokens on the server and gives the browser only a session cookie |
| Mobile or desktop app | Authorization Code + PKCE through the system browser, not an embedded web view (RFC 8252) |
| Service to service, no user | Client Credentials |
| TV, CLI, devices without a browser | Device Authorization Grant (RFC 8628) |
| Avoid | Implicit flow (tokens in the URL fragment) and Resource Owner Password Credentials (the app handles the user's password). Current security guidance (the OAuth 2.0 Security Best Current Practice, RFC 9700) recommends against both, and OAuth 2.1 removes them. |
PKCE (Proof Key for Code Exchange, RFC 7636) stops a stolen authorization code from being redeemed by someone else. The client creates a random code_verifier, sends only its SHA-256 hash (code_challenge) in the authorization request, and must present the original verifier when exchanging the code for tokens. An attacker who intercepts the code (through a malicious app registered for the same redirect scheme, logs, or a referrer leak) cannot exchange it without the verifier. Current guidance recommends PKCE for all clients, including confidential ones, because it also defends against code-injection attacks.
import base64
import hashlib
import secrets
def make_pkce_pair() -> tuple[str, str]:
"""Return (code_verifier, code_challenge) for the S256 method (RFC 7636)."""
verifier = secrets.token_urlsafe(64) # 86 URL-safe chars; the spec allows 43-128
digest = hashlib.sha256(verifier.encode("ascii")).digest()
challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
return verifier, challenge
def challenge_for(verifier: str) -> str:
digest = hashlib.sha256(verifier.encode("ascii")).digest()
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
# Test vector from RFC 7636, Appendix B
assert challenge_for("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") == "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
Other parameters and checks to mention:
state: random per request, bound to the user's session, checked on the callback. It prevents login CSRF (an attacker logging the victim into the attacker's account).nonce(OIDC): bound into the ID token, which prevents ID-token replay.- Exact redirect URI matching on the authorization server. Wildcards and prefix matching have caused many real token-theft bugs.
- ID token versus access token: the ID token is for the client (
aud= the client ID); the access token is for the API. Never send an ID token to an API as proof of access, and never parse an access token in the client to make security decisions.
Q45: Explain the cookie attributes HttpOnly, Secure, SameSite, Domain and the __Host- prefix.
| Attribute | Effect | Protects against |
|---|---|---|
HttpOnly | JavaScript cannot read the cookie through document.cookie | Session theft by XSS (XSS can still use the session while the page is open, but cannot exfiltrate the cookie) |
Secure | Sent only over HTTPS | Interception on plain HTTP |
SameSite=Strict | Never sent on cross-site requests, including clicking a link from another site | CSRF, but users arriving from links appear logged out |
SameSite=Lax | Sent on top-level GET navigations from other sites, not on cross-site POSTs, iframes or fetch | Most CSRF; a good default for session cookies |
SameSite=None | Sent on all cross-site requests; requires Secure | Nothing; only for genuine cross-site use such as embedded widgets |
Domain=example.com | Shared with all subdomains | Widens exposure: any subdomain (including a compromised or user-content one) receives it |
Path, Max-Age / Expires | Scope and lifetime | Shorter lifetime limits the damage from a stolen cookie |
__Host- name prefix | Browser enforces Secure, Path=/ and no Domain | Subdomains cannot set or overwrite it ("cookie tossing") |
Chromium-based browsers treat a cookie without SameSite as Lax, but not every browser does, so always set it explicitly.
import secrets
from flask import Flask, make_response
app = Flask(__name__)
@app.post("/login")
def login():
session_id = secrets.token_urlsafe(32) # opaque, random; the server stores what it maps to
response = make_response({"status": "ok"})
response.set_cookie(
"__Host-session",
session_id,
secure=True, # only sent over HTTPS
httponly=True, # not readable from JavaScript (limits XSS token theft)
samesite="Lax", # not sent on cross-site POSTs or subresource requests
path="/", # required by the __Host- prefix
max_age=60 * 60 * 8, # 8 hours; omit for a browser-session cookie
# no domain=...: the __Host- prefix forbids it, so the cookie stays on this exact host
)
return response
with app.test_client() as client:
print(client.post("/login").headers["Set-Cookie"])
# __Host-session=...; Expires=...; Max-Age=28800; Secure; HttpOnly; Path=/; SameSite=Lax
Session hygiene that goes with it: issue a new session ID at login and on privilege change (prevents session fixation), invalidate it server-side at logout, and use idle and absolute timeouts.
Q46: How does CSRF work, why is SameSite not a complete defence, and how do you protect a cookie-based app?
Cross-Site Request Forgery: the victim is logged in to bank.example. They visit evil.example, which auto-submits a form to https://bank.example/transfer. The browser attaches the bank's session cookie automatically, so the bank sees an authenticated request the user never intended.
CSRF only matters when the browser attaches credentials automatically: cookies (and HTTP Basic auth or client certificates). An API that requires an Authorization: Bearer ... header set by JavaScript is not CSRF-able, because another site cannot make the browser add that header. That design trades CSRF risk for XSS risk around where the token is stored.
Why SameSite=Lax alone is not enough:
- Same-site is not same-origin.
attacker.example.comandapp.example.comare the same site. A compromised or user-content subdomain can send requests that carrySameSite=Laxand evenStrictcookies. - State-changing
GETendpoints (GET /account/delete?confirm=1) are still exposed, because Lax allows cookies on top-levelGETnavigations. - Older browsers and some embedded web views do not support it consistently.
Layered defence:
- Never change state on
GET. SameSite=Lax(orStrict) session cookies.- A CSRF token for every unsafe method: the synchronizer-token pattern (random token stored in the session, sent in a form field or header), or a signed double-submit cookie.
- Check
Origin(orSec-Fetch-Site) on unsafe methods and reject foreign origins. - Re-authentication for very sensitive actions (change email, add payout account).
import hmac
import secrets
from urllib.parse import urlsplit
from flask import Flask, abort, request, session
app = Flask(__name__)
app.secret_key = secrets.token_bytes(32) # load from a secrets manager in real deployments
app.config.update(SESSION_COOKIE_SECURE=True, SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Lax")
TRUSTED_ORIGINS = {"https://app.example.com"}
UNSAFE_METHODS = {"POST", "PUT", "PATCH", "DELETE"}
def csrf_token() -> str:
if "csrf_token" not in session:
session["csrf_token"] = secrets.token_urlsafe(32)
return session["csrf_token"]
@app.before_request
def csrf_protect() -> None:
if request.method not in UNSAFE_METHODS:
return
# Layer 1: browsers send Origin on cross-origin POSTs; reject foreign origins.
origin = request.headers.get("Origin")
if origin is not None:
parts = urlsplit(origin)
if f"{parts.scheme}://{parts.netloc}" not in TRUSTED_ORIGINS:
abort(403)
# Layer 2: synchronizer token. A cross-site page cannot read it, so cannot send it.
sent = request.headers.get("X-CSRF-Token") or request.form.get("csrf_token", "")
expected = session.get("csrf_token", "")
if not expected or not hmac.compare_digest(sent, expected):
abort(403)
@app.get("/settings")
def settings_form():
# A real app renders this into a hidden form field or a meta tag for fetch() calls.
return {"csrf_token": csrf_token()}
@app.post("/settings/email")
def change_email():
return {"status": "updated"}
with app.test_client() as client:
base = "https://app.example.com"
token = client.get("/settings", base_url=base).json["csrf_token"]
ok = client.post("/settings/email", base_url=base, headers={"X-CSRF-Token": token, "Origin": base})
forged = client.post("/settings/email", base_url=base, headers={"Origin": "https://evil.example"})
print(ok.status_code, forged.status_code) # 200 403
In practice, use your framework's built-in protection (Django's CSRF middleware, Flask-WTF's CSRFProtect) rather than writing your own. The code above shows what those libraries do internally.
Q47: What does CORS actually protect, and what are the common CORS misconfigurations?
Browsers enforce the Same-Origin Policy: a script on https://evil.example may send a request to https://api.example.com, but it may not read the response. CORS is a way for the server to relax that rule for origins it trusts, through response headers such as Access-Control-Allow-Origin.
Key consequences:
- CORS is not an access-control mechanism for your API. It does not stop requests; curl, servers and attackers' scripts ignore it entirely. Authentication and authorization still have to happen on every request.
- CORS misconfiguration is a vulnerability, because it can let a malicious site read authenticated responses using the victim's cookies.
- Some cross-origin requests are sent without a preflight (simple
GETand form-stylePOSTs), so CORS never protects you from the side effects of a request. That is CSRF's job (Q46).
The dangerous misconfigurations:
- Reflecting the
Originheader back withAccess-Control-Allow-Credentials: true. Every website can now read your users' data. - Broken matching:
origin.endswith("example.com")also matcheshttps://evil-example.com; an unanchored regex has the same problem. - Allowing
null: sandboxed iframes and some redirects sendOrigin: null, so an attacker can produce it on demand. - Trusting every subdomain, so one XSS on a forgotten subdomain becomes data theft from the main API.
- Forgetting
Vary: Origin, so a CDN caches one origin's CORS headers and serves them to another.
Note that browsers refuse Access-Control-Allow-Origin: * together with credentials, which is exactly why developers reach for "reflect the origin", the most dangerous fix.
ALLOWED_ORIGINS = {"https://app.example.com", "https://admin.example.com"}
# VULNERABLE (do not use): reflects whatever Origin the browser sent, with credentials.
def cors_headers_vulnerable(origin: str) -> dict[str, str]:
return {"Access-Control-Allow-Origin": origin, "Access-Control-Allow-Credentials": "true"}
# SAFE: exact match against an allowlist, and tell caches the response varies by Origin.
def cors_headers(origin: str | None) -> dict[str, str]:
headers = {"Vary": "Origin"}
if origin in ALLOWED_ORIGINS:
headers["Access-Control-Allow-Origin"] = origin
headers["Access-Control-Allow-Credentials"] = "true"
return headers
print(cors_headers("https://app.example.com"))
# {'Vary': 'Origin', 'Access-Control-Allow-Origin': 'https://app.example.com', 'Access-Control-Allow-Credentials': 'true'}
print(cors_headers("https://evil-example.com")) # {'Vary': 'Origin'} -> the browser blocks the read
print(cors_headers("null")) # {'Vary': 'Origin'}
With FastAPI or Starlette, use CORSMiddleware with an explicit allow_origins=[...] list, and avoid allow_origin_regex unless the pattern is anchored and reviewed. For a public, unauthenticated, read-only API, Access-Control-Allow-Origin: * without credentials is fine.
Q48: What are the three types of XSS, and how does a nonce-based Content Security Policy stop them?
Cross-site scripting runs attacker-controlled JavaScript in your origin, where it can act as the user: read data, call APIs, change settings.
| Type | Where the payload lives | Example |
|---|---|---|
| Stored | Saved on the server and shown to other users | A comment or support-ticket subject containing a <script> tag |
| Reflected | In the request, echoed straight back in the response | A search page printing You searched for: <q> without encoding |
| DOM-based | Never touches the server; client-side JS writes untrusted data into the page | element.innerHTML = location.hash.slice(1) |
Primary defence: context-aware output encoding. Use a templating engine with autoescaping on (Jinja2 in Flask, Django templates, React's JSX) and avoid the escape hatches: |safe, Markup(...), mark_safe, dangerouslySetInnerHTML, innerHTML. Remember that encoding depends on context: HTML body, attribute, URL (javascript: URLs!) and inline JavaScript each need different rules. When users may submit rich HTML, sanitise it with an allowlist-based sanitiser on the server.
Second layer: a strict CSP. An allowlist CSP (script-src 'self' cdn.example.com) is often bypassable through scripts already hosted on allowed domains. A nonce-based policy is stronger: only <script> tags carrying the per-response random nonce run, so an injected tag (which cannot know the nonce) is blocked. 'strict-dynamic' lets those trusted scripts load their own dependencies.
import secrets
from flask import Flask, g, render_template_string, request
app = Flask(__name__)
PAGE = """<!doctype html>
<h1>Hello, {{ name }}</h1>
<script nonce="{{ csp_nonce }}">
document.querySelector("h1").dataset.ready = "1";
</script>
"""
@app.before_request
def make_nonce() -> None:
g.csp_nonce = secrets.token_urlsafe(16) # new, unpredictable value for every response
@app.after_request
def set_csp(response):
response.headers["Content-Security-Policy"] = (
f"script-src 'nonce-{g.csp_nonce}' 'strict-dynamic'; "
"object-src 'none'; "
"base-uri 'none'; "
"frame-ancestors 'none'"
)
return response
@app.get("/hello")
def hello():
name = request.args.get("name", "world")
# Jinja2 autoescaping turns markup in `name` into harmless text.
return render_template_string(PAGE, name=name, csp_nonce=g.csp_nonce)
with app.test_client() as client:
resp = client.get("/hello", query_string={"name": "<script>alert(1)</script>"})
print(resp.status_code, "<script>alert(1)</script>" in resp.text) # 200 True
print(resp.headers["Content-Security-Policy"].startswith("script-src 'nonce-")) # True
Rollout tips: start with Content-Security-Policy-Report-Only and a reporting endpoint to find inline handlers (onclick=) you must refactor; never reuse a nonce across responses; and for DOM XSS in large front ends, consider Trusted Types (require-trusted-types-for 'script') which makes dangerous DOM sinks reject plain strings. Keep session cookies HttpOnly too: it does not stop XSS, but it stops the cookie being stolen.
Q49: Which HTTP security headers should a modern web app or API send, and which are obsolete?
| Header | Recommended value | Purpose |
|---|---|---|
Strict-Transport-Security | max-age=63072000; includeSubDomains (add preload only after confirming every subdomain supports HTTPS) | Browser refuses plain HTTP to your domain, defeating SSL-stripping |
Content-Security-Policy | Nonce-based for HTML (Q48); for JSON APIs something like default-src 'none'; frame-ancestors 'none' | Limits script execution and framing |
X-Content-Type-Options | nosniff | Stops browsers guessing a different MIME type (e.g. treating an upload as script) |
frame-ancestors (CSP) | 'none' or 'self' | Clickjacking protection; supersedes X-Frame-Options, though sending X-Frame-Options: DENY too is harmless for old browsers |
Referrer-Policy | strict-origin-when-cross-origin or no-referrer | Prevents full URLs (which may contain tokens) leaking to other sites |
Permissions-Policy | camera=(), microphone=(), geolocation=() | Disables powerful browser features you do not use |
Cross-Origin-Opener-Policy | same-origin | Isolates your window from cross-origin popups |
Cache-Control | no-store on authenticated or sensitive responses | Keeps personal data out of shared caches and the browser's disk cache |
Obsolete or harmful:
X-XSS-Protection: the browser XSS auditors it controlled have been removed from modern browsers, and the filter itself could be abused to create information leaks. Do not enable it; send0or omit it.Public-Key-Pins(HPKP): removed from browsers because a mistake could lock users out of your site.Server/X-Powered-Bywith versions: remove them. Hiding versions is not a real control, but there is no reason to help automated scanners.
from flask import Flask
app = Flask(__name__)
SECURITY_HEADERS = {
"Strict-Transport-Security": "max-age=63072000; includeSubDomains",
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": "default-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
"Cross-Origin-Opener-Policy": "same-origin",
"X-XSS-Protection": "0", # disable the legacy filter explicitly
}
@app.after_request
def add_security_headers(response):
for name, value in SECURITY_HEADERS.items():
response.headers.setdefault(name, value) # let specific routes override
if response.mimetype == "application/json":
response.headers.setdefault("Cache-Control", "no-store") # API data should not sit in shared caches
response.headers.pop("Server", None)
return response
@app.get("/api/me")
def me():
return {"id": 42}
with app.test_client() as client:
r = client.get("/api/me")
print(r.headers["Cache-Control"], r.headers["X-Content-Type-Options"]) # no-store nosniff
Headers are usually best set once at the edge (reverse proxy, CDN or ingress) and verified by an automated check in CI or a scanner, so a new service cannot ship without them. The application still owns Content-Security-Policy when it uses per-response nonces.
Passwords, Secrets and Abuse Protection
Q50: How should you store passwords in 2026: argon2id, bcrypt, salts, peppers and upgrading old hashes?
Passwords must be stored with a slow, salted, memory-hard password-hashing function, never encrypted (encryption is reversible) and never with a fast hash like MD5, SHA-1 or plain SHA-256 (GPUs compute billions per second).
| Algorithm | Status | Notes |
|---|---|---|
| Argon2id | First choice | Memory-hard, so GPU and ASIC cracking is expensive. OWASP's minimum guidance is 19 MiB of memory, 2 iterations, parallelism 1, or an equivalent trade-off. |
| scrypt | Good | Also memory-hard |
| bcrypt | Acceptable for existing systems | Use a work factor of at least 10. Only the first 72 bytes of input are used, so very long passphrases are truncated (some library versions raise an error instead). |
| PBKDF2 | When FIPS compliance requires it | Needs a very high iteration count; not memory-hard |
Key ideas:
- Salt: a unique random value per password, stored with the hash, so identical passwords have different hashes and precomputed tables are useless. Modern libraries generate and embed it for you.
- Pepper (optional): a secret key, kept outside the database (for example in a KMS or HSM), applied with HMAC before hashing. It protects you when only the database leaks.
- Tune the cost so one hash takes a few hundred milliseconds on your hardware, and raise it over time.
- Upgrade on login: when a user logs in successfully with an old or weaker hash, re-hash the plaintext you now have with the current parameters. For a legacy MD5 or SHA-1 database, you can immediately wrap every stored hash (
argon2id(old_hash)) rather than waiting for each user to log in. - Do not leak which users exist: run a hash computation even when the user is not found, so timing does not reveal valid usernames.
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
# argon2-cffi's defaults use Argon2id with RFC 9106's recommended low-memory profile.
# Tune memory_cost/time_cost so one hash takes a few hundred milliseconds on your servers.
ph = PasswordHasher()
# A real dummy hash, so unknown users cost the same CPU time as real ones (no user enumeration by timing).
_DUMMY_HASH = ph.hash("dummy-password-for-timing")
def hash_password(password: str) -> str:
return ph.hash(password) # salt is generated and embedded in the encoded hash
def verify_and_upgrade(stored_hash: str | None, password: str) -> tuple[bool, str | None]:
"""Return (is_valid, new_hash_to_store_or_None)."""
try:
ph.verify(stored_hash or _DUMMY_HASH, password)
except (VerifyMismatchError, VerificationError, InvalidHashError):
return False, None
if stored_hash is None:
return False, None
if ph.check_needs_rehash(stored_hash): # parameters were raised since this hash was made
return True, ph.hash(password)
return True, None
stored = hash_password("correct horse battery staple")
print(stored.split("$")[1:4]) # ['argon2id', 'v=19', 'm=65536,t=3,p=4']
print(verify_and_upgrade(stored, "correct horse battery staple")[0]) # True
print(verify_and_upgrade(stored, "wrong")[0]) # False
print(verify_and_upgrade(None, "anything")[0]) # False, after doing a full hash computation
Password policy matters as much as storage. Current NIST guidance (SP 800-63B) favours length over complexity rules, checking new passwords against lists of breached passwords (Q52), and not forcing periodic changes unless there is evidence of compromise.
Q51: How do you give workloads cloud credentials without long-lived secret keys?
Long-lived access keys (an AWS_ACCESS_KEY_ID in a CI variable or a Kubernetes secret) are the most common credential found in leaks. They never expire, they are copied everywhere, and rotation is manual. The modern answer is workload identity federation: the workload proves what it is using an identity token issued by the platform it runs on, and exchanges that token for short-lived cloud credentials.
| Where the code runs | Mechanism |
|---|---|
| EC2, ECS, Lambda | IAM role attached to the compute; the SDK fetches temporary credentials automatically |
| Kubernetes (EKS, GKE, AKS) | Kubernetes service account mapped to a cloud identity (EKS IAM Roles for Service Accounts or Pod Identity, GKE Workload Identity, Azure Workload Identity) |
| GitHub Actions, GitLab CI | The CI provider's OIDC token is exchanged for a cloud role, restricted to a specific repository and branch |
| Databases | A secrets manager issuing dynamic per-workload credentials with a short lease (for example HashiCorp Vault's database secrets engine), or IAM database authentication |
Example: GitHub Actions deploying to AWS with no stored keys. The trust policy only lets the main branch of one repository assume the role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:acme/billing-api:ref:refs/heads/main"
}
}
}
]
}
# .github/workflows/deploy.yml
permissions:
id-token: write # allow the job to request an OIDC token
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/billing-api-deploy
aws-region: eu-west-1
- run: aws sts get-caller-identity # temporary credentials, expire automatically
import boto3
# No keys in code or config: boto3's default credential chain picks up the role
# credentials provided by the platform (instance role, IRSA/Pod Identity, CI OIDC).
s3 = boto3.client("s3")
# VULNERABLE (do not do this):
# s3 = boto3.client("s3", aws_access_key_id="AKIA...", aws_secret_access_key="...")
The common mistake to call out: a trust policy that checks aud but not sub, or uses a wildcard like repo:acme/*, which lets any repository (or any branch, including a pull-request branch) in the organisation assume a production role. Combine federation with least privilege on the role itself: one role per workload, scoped to the exact resources it needs.
Q52: How do you protect a login endpoint against brute force and credential stuffing?
- Brute force: many passwords tried against one account.
- Password spraying: one or two common passwords tried against many accounts, staying under per-account limits.
- Credential stuffing: username/password pairs leaked from other sites, replayed against yours from thousands of IPs. Each account sees one or two attempts and each IP looks like a normal user, so naive per-IP limits miss it.
No single control works, so layer them:
| Layer | What it does |
|---|---|
| MFA (phishing-resistant where possible: passkeys/WebAuthn) | Makes a correct password insufficient. The most effective control by far. |
| Rate limits on several keys | Per account, per IP, per IP range or ASN, plus a global failed-login rate. Per-account limits stop brute force; global and network-level limits catch stuffing and spraying. |
| Progressive delays or step-up challenges instead of hard lockout | Hard lockout lets an attacker lock out any user (denial of service). Prefer increasing delays, CAPTCHA, or "verify by email" after failures. |
| Breached-password checks at sign-up, password change and login | Rejects passwords already in public breach corpora, which is exactly what stuffing uses. |
| Uniform responses | Same message and similar timing for "unknown user" and "wrong password" (Q50). |
| Bot and device signals | Device fingerprinting, known-bad IP reputation, headless-browser detection, usually from a WAF or bot-management service. |
| Detection and response | Alert on the global login-failure ratio and on successful logins from new devices; notify users of new sign-ins; force resets for accounts confirmed compromised. |
import time
from collections import defaultdict, deque
class SlidingWindowLimiter:
"""In-memory sketch. With several app instances, keep these counters in Redis."""
def __init__(self, limit: int, window_seconds: float) -> None:
self.limit = limit
self.window = window_seconds
self._hits: dict[str, deque[float]] = defaultdict(deque)
def hit(self, key: str) -> bool:
"""Record an attempt; return False if the key is over its limit."""
now = time.monotonic()
hits = self._hits[key]
while hits and hits[0] <= now - self.window:
hits.popleft()
if len(hits) >= self.limit:
return False
hits.append(now)
return True
per_ip = SlidingWindowLimiter(limit=20, window_seconds=60) # one source hammering many accounts
per_account = SlidingWindowLimiter(limit=5, window_seconds=300) # many sources hammering one account
def check_login_allowed(ip: str, username: str) -> bool:
# Normalise the username so "Alice" and "alice " share a counter.
# Check BOTH limits on every attempt; do not short-circuit, or one limit stops counting.
ip_ok = per_ip.hit(f"ip:{ip}")
account_ok = per_account.hit(f"acct:{username.strip().lower()}")
return ip_ok and account_ok
results = [check_login_allowed("203.0.113.7", "alice") for _ in range(7)]
print(results) # [True, True, True, True, True, False, False]
Breached-password checking without sending the password anywhere, using the Have I Been Pwned range API (k-anonymity: only the first five hex characters of the SHA-1 hash leave your server):
import hashlib
import httpx
def is_breached_password(password: str) -> bool:
"""Check Have I Been Pwned's range API. Only the first 5 hex chars of the SHA-1 leave the server."""
digest = hashlib.sha1(password.encode("utf-8")).hexdigest().upper()
prefix, suffix = digest[:5], digest[5:]
response = httpx.get(f"https://api.pwnedpasswords.com/range/{prefix}", timeout=3.0)
response.raise_for_status()
for line in response.text.splitlines():
candidate, _, _count = line.partition(":")
if candidate == suffix:
return True
return False
SHA-1 is acceptable here because it is only used as a lookup key for a public dataset, not to store passwords. Decide in advance whether a failure of the external check should block sign-up (fail closed) or let it proceed (fail open, usually preferred for availability).
Senior / Principal — API and Application Security Scenarios
Q53: A customer reports seeing another company's invoices in your multi-tenant SaaS
Level: Senior / Principal
Scenario: A B2B SaaS serves 3,000 tenant companies from one shared database, with a tenant_id column on every table. A customer's admin emails support: after changing the number in the URL /api/invoices/1002, they saw an invoice belonging to a different company. A quick check finds that 4 of 140 endpoints load objects by ID without filtering by tenant. Access logs show one IP has been enumerating invoice IDs for two weeks.
Impact: Cross-tenant data breach: names, addresses, amounts and bank details of other customers. Contractual breach notifications, likely regulatory reporting (for example under GDPR), and serious damage to trust in a product whose core promise is isolation.
Root Cause: Broken Object Level Authorization (BOLA / IDOR, API1) at the design level. Tenant isolation depended on every developer remembering to add WHERE tenant_id = ... to every query. Authentication worked; object-level authorization was missing. Sequential IDs made enumeration trivial, and there was no alert on a single client requesting thousands of different objects.
Fix:
- Contain: patch the four endpoints, block the enumerating client, and preserve logs for the investigation.
- Scope by construction: handlers never query models directly; they use a repository that is created from the authenticated principal and always applies the tenant filter. The tenant comes from the verified session or token, never from the URL or body.
- Enforce in the database too: PostgreSQL Row-Level Security as a second, independent layer, so a forgotten filter returns no rows instead of another tenant's rows.
- Return 404, not 403, for objects in another tenant, so attackers cannot confirm which IDs exist.
- Test and detect: automated cross-tenant tests for every endpoint (user from tenant A requests tenant B's object IDs), plus alerts on high numbers of distinct object IDs or 404s per user.
- Non-sequential IDs (UUIDs) as defence in depth only; they reduce guessing but are not authorization.
from dataclasses import dataclass
from sqlalchemy import String, create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
class Base(DeclarativeBase):
pass
class Invoice(Base):
__tablename__ = "invoices"
id: Mapped[int] = mapped_column(primary_key=True)
tenant_id: Mapped[int] = mapped_column(index=True)
customer: Mapped[str] = mapped_column(String(100))
amount_cents: Mapped[int]
@dataclass(frozen=True)
class Principal:
user_id: int
tenant_id: int # taken from the verified token/session, NEVER from the URL or body
class NotFound(Exception):
pass
class InvoiceRepository:
"""The only way handlers can read invoices. Every query is tenant-scoped by construction."""
def __init__(self, session: Session, principal: Principal) -> None:
self._session = session
self._tenant_id = principal.tenant_id
def get(self, invoice_id: int) -> Invoice:
stmt = select(Invoice).where(Invoice.id == invoice_id, Invoice.tenant_id == self._tenant_id)
invoice = self._session.scalars(stmt).one_or_none()
if invoice is None:
raise NotFound # 404, not 403: do not confirm that the ID exists in another tenant
return invoice
def list(self, limit: int = 50) -> list[Invoice]:
stmt = select(Invoice).where(Invoice.tenant_id == self._tenant_id).order_by(Invoice.id).limit(min(limit, 100))
return list(self._session.scalars(stmt))
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add_all(
[
Invoice(id=1001, tenant_id=1, customer="Acme Ltd", amount_cents=12_000),
Invoice(id=1002, tenant_id=2, customer="Globex", amount_cents=99_000),
]
)
session.commit()
repo = InvoiceRepository(session, Principal(user_id=7, tenant_id=1))
print(repo.get(1001).customer) # Acme Ltd
try:
repo.get(1002) # another tenant's invoice
except NotFound:
print("1002 -> 404 Not Found")
print([i.id for i in repo.list()]) # [1001]
-- PostgreSQL Row-Level Security: the database enforces isolation even if a query forgets the filter
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY; -- also applies to the table owner
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::bigint)
WITH CHECK (tenant_id = current_setting('app.tenant_id')::bigint);
-- The application sets the tenant at the start of every transaction (true = local to this transaction):
-- SELECT set_config('app.tenant_id', '1', true);
-- Superusers and roles with BYPASSRLS ignore policies, so the app must not connect as one.
Workflow Diagram:
Request: GET /api/invoices/1002 (token: user 7, tenant 1)
|
v
AuthN: verify token --> Principal(user=7, tenant=1) <- tenant from token, not from URL
|
v
InvoiceRepository(principal).get(1002)
| SQL: ... WHERE id = 1002 AND tenant_id = 1
v
Postgres RLS: tenant_id = current_setting('app.tenant_id') <- second, independent check
|
v
0 rows --> 404 Not Found (+ metric: distinct-ID / 404 rate per user for enumeration alerts)
Interviewer Notes: The senior answer fixes the endpoints. The principal answer changes the architecture so the bug class cannot recur: tenant-scoped data access as the only path, database-level enforcement, cross-tenant tests in CI, and detection. Good candidates also handle the incident properly: scope the exposure from logs (which objects did the enumerating client actually receive?), legal and customer notification, and a decision on whether other isolation models (schema-per-tenant, database-per-tenant for large customers) are worth their operational cost.
Red Flags: "Switch to UUIDs" as the fix. Reading tenant_id from a request parameter or header. Returning 403 for other tenants' objects (confirms existence). Fixing only the four reported endpoints without asking how the other 136 are protected. Connecting the app as a database superuser, which silently bypasses RLS.
Q54: SSRF in a "fetch URL preview" feature exposes cloud credentials
Level: Senior / Principal
Scenario: A chat product generates link previews: when a user pastes a URL, the backend fetches the page and extracts the title and image. A researcher reports that pasting http://169.254.169.254/latest/meta-data/iam/security-credentials/ returns the name of the instance's IAM role, and a follow-up URL returns temporary AWS credentials in the preview text. The role has read access to several S3 buckets.
Impact: Anyone with an account could obtain cloud credentials, read internal S3 data, and probe internal services (admin panels, Redis, Elasticsearch) that trust the private network. Server-side request forgery is how several well-known cloud breaches started.
Root Cause:
- SSRF (API7 / A10): the server fetches arbitrary user-supplied URLs with no destination validation and follows redirects.
- The instance metadata service accepted simple
GETrequests (IMDSv1), so a basic SSRF was enough to read credentials. - The preview service ran with a broad IAM role and unrestricted network egress.
Fix (layers, since URL validation alone is easy to get wrong):
- Network egress control (strongest): run fetchers in an isolated network segment, or send them through an egress proxy that blocks private, loopback, link-local and metadata ranges.
- Require IMDSv2 (session tokens obtained by a
PUTwith a custom header, which a typical SSRF cannot send) and set the response hop limit to 1 where containers do not need metadata access. - Validate the destination after DNS resolution: allowed schemes and ports only, reject any resolved address that is not public, and handle IPv4-mapped IPv6 and odd encodings by checking the resolved address rather than parsing strings.
- Do not follow redirects automatically; if you must, re-validate each hop.
- Prevent DNS rebinding: connect to the IP you validated (or let the egress proxy resolve and enforce), so a second DNS lookup cannot return a different, internal address.
- Least privilege: the preview service needs no cloud permissions at all.
- Return only the extracted fields (title, image), never raw response bodies or detailed error messages.
import ipaddress
import socket
from urllib.parse import urlsplit
ALLOWED_SCHEMES = {"https"}
ALLOWED_PORTS = {443}
class UnsafeURL(ValueError):
pass
def _is_public(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
ip = ip.ipv4_mapped # ::ffff:169.254.169.254 must be judged as 169.254.169.254
return ip.is_global and not ip.is_multicast
def validate_outbound_url(url: str) -> tuple[str, list[str]]:
"""Return (hostname, resolved public IPs) or raise UnsafeURL."""
parts = urlsplit(url)
if parts.scheme not in ALLOWED_SCHEMES:
raise UnsafeURL(f"scheme not allowed: {parts.scheme!r}")
if parts.username or parts.password:
raise UnsafeURL("credentials in URL not allowed")
host = parts.hostname
if not host:
raise UnsafeURL("missing host")
port = parts.port or 443
if port not in ALLOWED_PORTS:
raise UnsafeURL(f"port not allowed: {port}")
try:
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
except socket.gaierror as exc:
raise UnsafeURL(f"cannot resolve {host}") from exc
ips = sorted({info[4][0] for info in infos})
for raw_ip in ips:
if not _is_public(ipaddress.ip_address(raw_ip.split("%")[0])):
# Reject if ANY resolved address is internal: attackers mix public and private records.
raise UnsafeURL(f"{host} resolves to non-public address {raw_ip}")
return host, ips
for candidate in [
"http://169.254.169.254/latest/meta-data/", # cloud metadata, wrong scheme anyway
"https://169.254.169.254/latest/meta-data/", # link-local
"https://127.0.0.1/admin", # loopback
"https://[::ffff:10.0.0.5]/", # IPv4-mapped IPv6 private address
"https://10.0.0.5:8443/", # port not allowed
"https://user:pass@example.com/", # credentials
]:
try:
validate_outbound_url(candidate)
print("ALLOWED ", candidate)
except UnsafeURL as exc:
print("BLOCKED ", candidate, "->", exc)
When you then fetch, disable redirects (httpx does not follow them unless you pass follow_redirects=True; with requests pass allow_redirects=False), set short timeouts and a maximum response size, and prefer an egress proxy that re-checks the destination itself to close the DNS-rebinding gap.
# Require IMDSv2 and keep metadata unreachable from containers on this instance
aws ec2 modify-instance-metadata-options \
--instance-id i-0123456789abcdef0 \
--http-tokens required \
--http-put-response-hop-limit 1
Workflow Diagram:
user URL --> [scheme/port/userinfo checks] --> [DNS resolve] --> [every IP public?] --no--> 400
|yes
v
[egress proxy: blocks 10/8, 172.16/12, 192.168/16, 127/8, 169.254/16, ::1, fc00::/7]
|
v
fetch (no redirects, 3 s timeout, 1 MB cap) --> extract title/image only
Even if all of the above fail: IMDSv2 + hop limit 1 + no IAM role on the fetcher = no credentials to steal
Interviewer Notes: Look for defence in depth across layers: application validation, network egress, cloud metadata hardening and IAM. Candidates who rely only on a regex or a hostname blocklist have not seen the bypasses (decimal or octal IP notation, IPv6, DNS names that resolve to internal IPs, open redirects on allowed domains, DNS rebinding). Principal candidates make "fetch a user-supplied URL" a shared platform capability (one hardened fetcher service) instead of something every team implements.
Red Flags: Blocklisting the string 169.254.169.254. Validating the hostname but not the resolved IP. Following redirects. Giving the fetcher the same broad IAM role as the main app. Returning the fetched body or error details to the user.
Q55: A production API key was pushed to a public GitHub repository and is already being abused
Level: Senior
Scenario: A developer pushed a small demo project to their public GitHub account. It contained the company's production payment-provider API key and an AWS access key for a CI user. Forty minutes later, the AWS bill alarm fires: dozens of large GPU instances are running in regions the company never uses. The payment provider also emails to say the key appeared in a public repository.
Impact: Direct financial loss (cloud mining), possible data access through the AWS user's permissions, potential fraudulent refunds through the payment key, and an incident that must be scoped and possibly reported.
Root Cause: Long-lived, broadly scoped secrets copied into a developer's local project; no pre-commit or push-time secret scanning on personal repositories; and an AWS user with far more permissions than its CI job needed. Public repositories are scanned by attackers' bots within minutes of a push.
Fix: The order matters. Revoke first, clean up later. Deleting the repository or rewriting history does not help once the key has been public: it has already been copied.
- Revoke or deactivate both keys immediately, and issue replacements to the systems that legitimately need them.
- Contain the abuse: terminate the unexpected resources, check for persistence (new IAM users, access keys, roles, Lambda functions, changed trust policies), and add a deny policy if needed.
- Scope the blast radius from audit logs: every API call made with the leaked key since it was first pushed.
- Fix the causes: replace the CI access key with OIDC federation (Q51); restrict the payment key's permissions and IP range if the provider supports it; enable GitHub secret scanning and push protection; add a pre-commit secret scanner; and use identifiable key prefixes for your own API keys so scanners can find them.
- Blameless postmortem (the developer reporting quickly is what you want to encourage).
# 1. Disable the leaked AWS key at once (AKIAIOSFODNN7EXAMPLE is AWS's documentation example ID)
aws iam update-access-key --user-name ci-deployer --access-key-id AKIAIOSFODNN7EXAMPLE --status Inactive
# 2. What did the key do? CloudTrail lookup by access key
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIAIOSFODNN7EXAMPLE \
--max-results 50
# 3. Look for persistence: keys or users created recently
aws iam list-users
aws iam list-access-keys --user-name ci-deployer
# 4. Once the investigation no longer needs it, delete the key permanently
aws iam delete-access-key --user-name ci-deployer --access-key-id AKIAIOSFODNN7EXAMPLE
lookup-events only covers recent management events in one region. For a full investigation, query the CloudTrail logs delivered to S3 across all regions.
If you issue API keys to your customers, design them so leaks are detectable and revocation is cheap:
import hashlib
import hmac
import secrets
import zlib
PREFIX = "acme_live_" # distinctive prefix: secret scanners and grep can find leaked keys
def generate_api_key() -> tuple[str, str]:
"""Return (key_to_show_once, digest_to_store)."""
body = secrets.token_urlsafe(30)
checksum = format(zlib.crc32(body.encode()), "08x") # lets scanners discard random look-alikes offline
key = f"{PREFIX}{body}_{checksum}"
return key, hashlib.sha256(key.encode()).hexdigest()
def looks_like_our_key(candidate: str) -> bool:
if not candidate.startswith(PREFIX):
return False
body, _, checksum = candidate[len(PREFIX):].rpartition("_")
return bool(body) and checksum == format(zlib.crc32(body.encode()), "08x")
def verify_api_key(presented: str, stored_digest: str) -> bool:
presented_digest = hashlib.sha256(presented.encode()).hexdigest()
return hmac.compare_digest(presented_digest, stored_digest)
key, digest = generate_api_key()
print(looks_like_our_key(key), verify_api_key(key, digest)) # True True
print(looks_like_our_key("acme_live_notarealkey_00000000")) # False
Store only the digest (like a password, but a fast hash is fine because the key is long and random), show the key once, support several active keys per customer so they can rotate without downtime, and record last_used_at so unused keys can be expired.
Workflow Diagram:
Leak detected (bill alarm / provider notice / secret-scanning alert)
|
v
REVOKE keys (minutes) --> issue replacements to legitimate systems
|
v
CONTAIN: kill rogue resources, hunt persistence (new users, keys, roles)
|
v
SCOPE: CloudTrail / provider logs for every call made with the key
|
v
FIX ROOT CAUSES: OIDC instead of static keys, least privilege,
push protection + pre-commit scanning, prefixed keys
|
v
Blameless postmortem + customer/regulator notification if data was accessed
Interviewer Notes: The key insight: once public, a secret is compromised; rotation is the fix, history rewriting is hygiene. Strong candidates think about persistence (attackers create their own keys so your revocation does not lock them out), about the blast radius (what could this key do, and what did it do?), and about removing the class of problem with short-lived, federated credentials. Bonus: GitHub's secret-scanning partner programme notifies some providers automatically, which is how the payment provider knew.
Red Flags: "Delete the repo and force-push" as the first step. Rotating only the key that was abused. Not checking for attacker persistence. Blaming the developer. Replacing the leaked static key with another static key.
Q56: Account takeover through the password reset flow
Level: Senior
Scenario: Several users report that their accounts were taken over even though they use strong, unique passwords and nobody asked them for a code. Logs show successful password resets that the users never requested. Investigation of the reset flow finds:
- The reset link is built from the request's
Hostheader. - Tokens are 6-digit numbers, valid for 7 days, and can be used more than once.
- The raw token is stored in the database.
- The "forgot password" page says "No account with that email" for unknown addresses.
- Existing sessions stay logged in after a reset.
Impact: Full account takeover without knowing the password, which bypasses MFA too if the reset flow does not require it. Attackers can also enumerate which emails have accounts.
Root Cause: The reset flow is an authentication mechanism but was designed like a convenience feature:
- Host header poisoning: an attacker requests a reset for the victim's email with
Host: attacker.example. The victim receives a genuine email from your domain, but the link points at the attacker's site. One click hands over the token. - Guessable, long-lived, reusable tokens: one million possible values, seven days to guess, no rate limit.
- Plaintext tokens at rest: a read-only database leak (or SQL injection) yields valid reset tokens.
- User enumeration tells attackers which emails to target.
- No session revocation: an attacker who is already logged in stays logged in after the victim resets.
Fix:
- Build links from a configured base URL, never from request headers. Also configure an allowlist of trusted hosts at the framework or proxy (Django's
ALLOWED_HOSTS, for example). - Tokens: at least 128 bits from
secrets, hashed at rest, single use, short expiry (15–60 minutes), and invalidated when a new one is issued or the password changes. - Identical response for known and unknown emails, and rate-limit reset requests per account and per IP.
- After a reset: revoke all sessions and refresh tokens, notify the user by email, and require MFA (if enrolled) before the new password takes effect.
- Put the token in the URL fragment (
#token=...) or have the landing page exchange it immediately, so it does not leak throughRefererheaders or access logs.
import hashlib
import hmac
import secrets
import time
from dataclasses import dataclass, field
PUBLIC_BASE_URL = "https://app.example.com" # from configuration, NEVER from the request's Host header
RESET_TTL_SECONDS = 30 * 60
@dataclass
class ResetToken:
user_id: int
digest: str
expires_at: float
used: bool = False
@dataclass
class Store: # stands in for database tables
users_by_email: dict[str, int] = field(default_factory=dict)
reset_tokens: list[ResetToken] = field(default_factory=list)
revoked_sessions_for: set[int] = field(default_factory=set)
outbox: list[tuple[str, str]] = field(default_factory=list)
def _digest(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
def request_password_reset(store: Store, email: str) -> str:
user_id = store.users_by_email.get(email.strip().lower())
if user_id is not None:
# One active token per user: older unused tokens are invalidated.
store.reset_tokens = [t for t in store.reset_tokens if t.user_id != user_id]
token = secrets.token_urlsafe(32) # 256 bits of randomness
store.reset_tokens.append(ResetToken(user_id, _digest(token), time.time() + RESET_TTL_SECONDS))
store.outbox.append((email, f"{PUBLIC_BASE_URL}/reset-password#token={token}"))
# Identical response whether or not the account exists (no user enumeration).
return "If an account exists for that address, we have sent a reset link."
def complete_password_reset(store: Store, token: str, new_password: str) -> bool:
presented = _digest(token)
for record in store.reset_tokens:
if hmac.compare_digest(record.digest, presented):
if record.used or record.expires_at < time.time():
return False
record.used = True # single use (make this an atomic UPDATE in a real database)
# set_password(record.user_id, new_password) -> argon2id hash, see Q50
store.revoked_sessions_for.add(record.user_id) # log out every existing session
return True
return False
store = Store(users_by_email={"alice@example.com": 42})
print(request_password_reset(store, "alice@example.com"))
print(request_password_reset(store, "nobody@example.com")) # same message
token = store.outbox[-1][1].split("#token=")[1]
print(complete_password_reset(store, token, "a new long passphrase")) # True
print(complete_password_reset(store, token, "replay attempt")) # False: already used
print(42 in store.revoked_sessions_for) # True
In a real system, look the token up by its digest with an indexed query rather than scanning, and keep the "is it used / expired?" check and the update in one atomic statement.
Workflow Diagram:
VULNERABLE FIXED
attacker: POST /forgot (Host: evil.example) link built from PUBLIC_BASE_URL only
-> victim gets real email, link to evil.example token: 256-bit, hashed at rest, 30 min, single use
-> victim clicks -> token leaks to attacker same response for unknown emails + rate limit
-> attacker resets password reset -> revoke all sessions + notify user
-> attacker's old sessions still valid MFA (if enrolled) still required to sign in
Interviewer Notes: Strong candidates treat account recovery as the weakest authentication path, since attackers always pick the easiest door. They should spot Host-header poisoning, token entropy and storage, enumeration, and session revocation without prompting. Principal candidates add monitoring (alert on reset spikes, on resets followed by email or MFA changes, on resets from new countries) and consider recovery for MFA-enrolled users (recovery codes, support-desk verification that resists social engineering).
Red Flags: Using random instead of secrets. Numeric codes with no attempt limit. Building URLs from request.host. Different error messages for unknown emails. Not logging out other sessions. Allowing the reset to also change the account email.
Q57: A critical vulnerability is announced in a library three levels deep in your dependency tree
Level: Senior / Principal
Scenario: A critical remote-code-execution advisory is published for an image-parsing library, which we will call imgparse (a hypothetical name). Nobody at the company has heard of it. Leadership asks within the hour: "Are we affected, where, and when will it be fixed?" You run 60 Python services. In one of them the chain is reportkit (direct dependency) → pdfrender → imgparse, and reportkit's latest release still pins the vulnerable imgparse range.
Impact: If any internet-facing service passes user-uploaded files to the vulnerable parser, attackers may get code execution on that service. Not knowing your exposure for days is itself a business risk: customers and auditors will ask.
Root Cause: No central inventory of what each service actually runs (SBOMs), no automated vulnerability scanning tied to deployed versions, and transitive dependencies treated as "someone else's problem".
Fix:
- Find exposure in minutes, not days: query your SBOM store or dependency graph for
imgparseacross all services and deployed versions. Without SBOMs, scan each service's lockfile. - Assess reachability and exposure for each hit: does user input reach the vulnerable function? Is the service internet-facing?
- Patch in the least risky way:
- Upgrade the direct dependency if a fixed release exists.
- Otherwise override the transitive version with a constraint, and run the test suite to confirm compatibility.
- If no fixed version exists anywhere, apply compensating controls: disable the feature, restrict accepted file types, process uploads in a sandboxed worker with no network or credentials, or add a WAF rule if the exploit has a recognisable pattern.
- Communicate status per service (affected, not reachable, patched) and record VEX statements for "affected but not exploitable".
- Prevent the scramble next time: SBOM per build, scanning in CI and continuously against deployed versions, and automated update PRs.
# Who depends on imgparse in this service, and through which path?
pipdeptree --reverse --packages imgparse
# Option A: the direct dependency has a fixed release -> bump it in requirements.in, then re-lock
pip-compile --generate-hashes --upgrade-package reportkit requirements.in -o requirements.txt
# Option B: override only the transitive package with a constraints file
echo "imgparse>=4.2.1 # security: overrides the range pdfrender allows; remove when reportkit updates" > constraints.txt
pip install -r requirements.txt -c constraints.txt
# Verify nothing known-vulnerable remains (non-zero exit fails the build)
pip-audit -r requirements.txt
(The package names and the 4.2.1 version above are illustrative.)
# .github/workflows/dependency-audit.yml: scan on every PR and daily, so new advisories are caught
name: dependency-audit
on:
pull_request:
schedule:
- cron: "0 6 * * *"
jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install pip-audit
- run: pip-audit -r requirements.txt
Workflow Diagram:
Advisory published
|
v
Inventory: SBOM / lockfile search across 60 services --> 7 services include imgparse
|
v
Triage each: reachable with user input? internet-facing? --> 2 critical, 3 low, 2 not reachable
|
+--> critical: patch today (upgrade parent, or constraint override) + sandbox uploads
+--> low: patch this sprint
+--> not reachable: VEX statement, patch with the next routine update
|
v
Status page for leadership: affected / mitigated / patched, per service, with timestamps
|
v
Retro: SBOM coverage, continuous scanning, update-PR automation, sandboxed parsers
Interviewer Notes: A senior candidate can patch a transitive dependency safely. A principal candidate builds the capability to answer "are we affected?" within an hour across the whole estate, prioritises by real exploitability rather than by CVSS alone, and uses architecture (sandboxed parsing of untrusted files, minimal base images) to reduce how often such advisories matter. They also communicate clearly with leadership while the work is in progress.
Red Flags: "We'll wait for the direct dependency to update." Force-upgrading every package at once during an incident. Not knowing how to see the dependency tree. Treating every finding as equally urgent. Forgetting deployed container images that are not rebuilt from the latest lockfile.
Q58: Stored XSS in a support ticket hijacks an admin session
Level: Senior
Scenario: Customers open support tickets through a public form. Support agents read them in an internal admin dashboard that was built quickly "because only staff use it". An attacker submits a ticket whose subject contains an HTML payload. When an agent opens the ticket list, the payload runs in the admin dashboard's origin, reads the agent's session cookie (not HttpOnly), and sends it to the attacker. With the session, the attacker issues refunds and exports customer data. This is blind XSS: the attacker never sees the admin page; they just wait for staff to view it.
Impact: Full admin access through one support ticket: fraud, customer data export, and possibly privilege escalation to other internal tools that share the same single sign-on session.
Root Cause:
- The template rendered the subject with
|safebecause "subjects sometimes contain formatting". - Internal tools were treated as trusted, so they had no CSP, no security review, and session cookies readable from JavaScript.
- High-impact admin actions (refunds, exports) required no re-authentication.
- No separation between the origin that displays untrusted customer content and the origin that holds admin power.
Fix:
- Remove
|safeand rely on autoescaping. If rich text is genuinely needed, sanitise on the server with an allowlist sanitiser (for examplenh3). - Add a nonce-based CSP to the admin app (Q48) and make all session cookies
HttpOnly,Secure,SameSite. - Step-up authentication (fresh MFA) for refunds, exports and role changes; limits and alerts on bulk exports.
- Serve admin tools from a separate origin behind SSO, and render untrusted attachments or HTML in a sandboxed origin.
- Invalidate all admin sessions now, review audit logs for actions taken with the stolen session, and search the ticket database for other payloads.
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(["html"], default_for_string=True))
ticket = {"subject": '<img src=x onerror="alert(document.domain)">', "body": "Printer is on fire"}
# VULNERABLE: the |safe filter (or Markup(...)) disables escaping for attacker-controlled data.
vulnerable = env.from_string("<td>{{ ticket.subject|safe }}</td>").render(ticket=ticket)
# SAFE: default autoescaping renders the payload as inert text.
safe = env.from_string("<td>{{ ticket.subject }}</td>").render(ticket=ticket)
print(vulnerable) # <td><img src=x onerror="alert(document.domain)"></td>
print(safe) # <td><img src=x onerror="alert(document.domain)"></td>
import nh3
# When users may submit rich text, sanitise with an allowlist on the server.
clean = nh3.clean(
'<p>Hi <b>team</b> <img src=x onerror="alert(1)"><a href="javascript:alert(1)">link</a></p>',
tags={"p", "b", "i", "a", "ul", "ol", "li", "code", "pre"},
attributes={"a": {"href"}},
url_schemes={"https", "mailto"},
)
print(clean) # <p>Hi <b>team</b> <a rel="noopener noreferrer">link</a></p>
Workflow Diagram:
attacker --(ticket subject with HTML payload)--> public form --> tickets DB
|
support agent opens admin dashboard <--------------------------------+
|
v
VULNERABLE: {{ subject|safe }} --> script runs as admin origin --> cookie sent to attacker
|
FIXED LAYERS:
1. autoescape / allowlist sanitiser -> payload is text, never markup
2. CSP nonce -> injected script would not run anyway
3. HttpOnly cookie -> script could not read the session
4. step-up MFA for refunds/exports -> stolen session alone is not enough
5. separate admin origin + audit -> limited blast radius, fast detection
Interviewer Notes: The lesson interviewers want is that internal tools render external input, so "only staff use it" makes them a higher-value target, not a safer one. Good candidates recognise blind XSS, apply layered controls (encoding, CSP, cookie flags, step-up auth), and handle the incident: session invalidation, audit-log review and a search for other stored payloads.
Red Flags: A denylist that strips <script> (event-handler attributes and many other vectors remain). Sanitising on input but rendering with |safe elsewhere. "It's internal, so no CSP." Fixing the template without revoking sessions or reviewing what the attacker did.
Q59: Forged webhooks mark unpaid orders as paid
Level: Senior
Scenario: An e-commerce backend receives payment-provider webhooks at POST /webhooks/payments. When it gets {"type": "payment.succeeded", "order_id": ...} it marks the order paid and triggers shipping. Finance notices 40 shipped orders with no matching payment in the provider's dashboard. The endpoint URL had been visible in a public front-end bundle, and it accepted any JSON body.
Impact: Goods shipped without payment, inventory loss, and the same weakness may let attackers trigger refunds or subscription upgrades through other event types.
Root Cause:
- No authenticity check: the handler never verified the provider's signature, so anyone could send events.
- No replay protection: even signed events could have been replayed.
- Trusting event contents for a high-value state change without confirming with the provider (OWASP API10, Unsafe Consumption of APIs).
- No reconciliation between orders marked paid and the provider's records.
Fix:
- Verify the signature the provider sends, as an HMAC over a timestamp and the exact raw request body (parse JSON only after verification; re-serialising changes the bytes and breaks the signature). Use the provider's official SDK helper when one exists.
- Reject stale timestamps (for example older than 5 minutes) and de-duplicate by event ID, so captured requests cannot be replayed.
- For high-value transitions, fetch the payment or event from the provider's API by ID before acting, rather than trusting the payload.
- Make the handler idempotent: providers retry, and duplicate deliveries must not ship twice.
- Reconcile daily: orders marked paid versus settled payments, with alerts on mismatches.
- Keep the secret per endpoint in a secrets manager and support rotation (accept old and new secrets for a short overlap).
import hashlib
import hmac
import json
import time
WEBHOOK_SECRET = b"whsec_example_only" # per-endpoint secret from a secrets manager
TOLERANCE_SECONDS = 300
_seen_event_ids: set[str] = set() # use a database table or Redis with a TTL in production
class InvalidWebhook(Exception):
pass
def sign(timestamp: int, raw_body: bytes, secret: bytes = WEBHOOK_SECRET) -> str:
message = str(timestamp).encode() + b"." + raw_body
return hmac.new(secret, message, hashlib.sha256).hexdigest()
def verify_webhook(raw_body: bytes, timestamp_header: str, signature_header: str) -> dict:
# 1. Freshness: rejects replays of old captured requests.
try:
timestamp = int(timestamp_header)
except ValueError as exc:
raise InvalidWebhook("bad timestamp") from exc
if abs(time.time() - timestamp) > TOLERANCE_SECONDS:
raise InvalidWebhook("timestamp outside tolerance")
# 2. Authenticity + integrity: HMAC over timestamp AND the exact raw bytes received.
expected = sign(timestamp, raw_body)
if not hmac.compare_digest(expected, signature_header):
raise InvalidWebhook("bad signature")
# 3. Only now parse, and de-duplicate by event ID (replays inside the window, provider retries).
event = json.loads(raw_body)
if event["id"] in _seen_event_ids:
raise InvalidWebhook("duplicate event")
_seen_event_ids.add(event["id"])
return event
body = json.dumps({"id": "evt_123", "type": "payment.succeeded", "order_id": "o-9"}).encode()
ts = int(time.time())
print(verify_webhook(body, str(ts), sign(ts, body))["type"]) # payment.succeeded
for label, args in [
("forged", (body, str(ts), "0" * 64)),
("tampered", (body.replace(b"o-9", b"o-1"), str(ts), sign(ts, body))),
("replayed", (body, str(ts), sign(ts, body))),
("stale", (body, str(ts - 3600), sign(ts - 3600, body))),
]:
try:
verify_webhook(*args)
except InvalidWebhook as exc:
print(f"{label}: rejected ({exc})")
# forged: rejected (bad signature)
# tampered: rejected (bad signature)
# replayed: rejected (duplicate event)
# stale: rejected (timestamp outside tolerance)
Header names and the exact signing format differ between providers. The structure above (timestamp + raw body, HMAC-SHA256, constant-time compare, tolerance window, event-ID de-duplication) is the common pattern; follow your provider's documentation for the details.
Workflow Diagram:
POST /webhooks/payments
|
v
read RAW body bytes (do not parse yet)
|
v
timestamp within 5 min? --no--> 400
| yes
v
HMAC(secret, ts + "." + raw) == signature? (compare_digest) --no--> 400
| yes
v
event.id already processed? --yes--> 200 (idempotent no-op)
| no
v
high-value event? --> GET payment from provider API by ID --> amounts/status match?
|
v
apply state change in one transaction + record event.id --> 200
|
nightly reconciliation: orders "paid" vs provider settlements --> alert on mismatch
Interviewer Notes: Strong candidates know that a webhook endpoint is a public, unauthenticated API by default and must be authenticated by signature, not by obscurity of the URL. They mention raw-body handling (a classic framework pitfall), replay windows, idempotency and reconciliation. Principal candidates generalise to every inbound integration: never trust third-party data more than user input, and confirm high-value facts with the source of truth.
Red Flags: "The URL is secret." Verifying a signature over re-serialised JSON. Comparing signatures with ==. IP allowlisting as the only control. Non-idempotent handlers that ship twice on retries.
Q60: A forgotten v1 endpoint leaks the user database
Level: Senior / Principal
Scenario: Two years ago the team launched /v2 with a new authentication middleware attached to the v2 router. The old /v1 routes were "deprecated" but never removed, because an old mobile-app version still used one of them. A researcher decompiles that old app, finds GET /v1/users/export, and discovers it returns every user's email and phone number without any authentication. Nobody on the current team knew the route existed; it is not in the OpenAPI spec, the gateway configuration routes /* to the service, and the WAF rules only cover /v2.
Impact: A mass data leak through an endpoint the organisation did not know it was running. Security testing, monitoring and documentation all covered /v2 only.
Root Cause: Improper Inventory Management (API9) plus broken function-level authorization:
- No authoritative inventory of exposed endpoints, versions and hosts.
- Authentication attached per router, so routes outside the new router were unprotected by default.
- A gateway that forwarded every path instead of only known routes.
- Deprecation without a removal date, owner or traffic monitoring.
Fix:
- Contain: block
/v1/users/exportat the gateway immediately, and review access logs for past use. - Build the inventory from traffic, not from documentation: gateway and load-balancer logs show what is actually being called; diff that against the OpenAPI specs.
- Deny by default at the edge: the gateway routes only paths that exist in a reviewed spec; everything else gets a 404.
- Deny by default in the app: global authentication with explicit, reviewed opt-outs for public routes, plus a CI test that fails on any route without one (below).
- Retire versions properly: owner, announced removal date,
DeprecationandSunsetresponse headers, usage dashboards, then removal. - Include old versions, staging hosts and internal hostnames in security testing and asset discovery.
from fastapi import APIRouter, Depends, FastAPI, HTTPException
from fastapi.dependencies.models import Dependant
from fastapi.routing import APIRoute
def require_user() -> dict: # real version: verify the session or bearer token
raise HTTPException(status_code=401)
def public_endpoint() -> None:
"""Marker dependency: an explicit, reviewable opt-out from authentication."""
v2 = APIRouter(prefix="/v2", dependencies=[Depends(require_user)])
@v2.get("/users/export")
def export_users_v2() -> list[dict]:
return []
app = FastAPI()
app.include_router(v2)
@app.get("/health", dependencies=[Depends(public_endpoint)])
def health() -> dict:
return {"ok": True}
# The forgotten legacy route that caused the incident. With this test in CI, it fails the build.
@app.get("/v1/users/export")
def export_users_v1() -> list[dict]:
return []
AUTH_MARKERS = {require_user, public_endpoint}
def _dependency_calls(dependant: Dependant) -> set:
calls = set()
for dep in dependant.dependencies:
calls.add(dep.call)
calls |= _dependency_calls(dep)
return calls
def test_every_route_declares_auth_or_explicit_public():
unprotected = [
f"{sorted(route.methods)} {route.path}"
for route in app.routes
if isinstance(route, APIRoute) and not (_dependency_calls(route.dependant) & AUTH_MARKERS)
]
assert not unprotected, f"routes without auth: {unprotected}"
# AssertionError: routes without auth: ["['GET'] /v1/users/export"]
Workflow Diagram:
Discovery Control Lifecycle
--------- ------- ---------
gateway/LB access logs --+ edge: route only spec'd paths owner per endpoint
OpenAPI specs --+--> app: global auth, explicit Deprecation + Sunset headers
DNS / cloud asset scan --+ public opt-outs usage dashboard per version
old client binaries --+ CI: route-auth coverage test removal date enforced
|
v
diff(actual traffic, documented API) = shadow and zombie endpoints to fix or delete
Interviewer Notes: The principal insight is that you cannot secure what you do not know exists, and documentation always lags reality. Strong answers combine traffic-based discovery, deny-by-default at two layers, an automated guardrail in CI, and an API lifecycle process with owners and dates. Mentioning that mobile clients keep old versions alive for years (so version retirement needs forced-upgrade mechanisms) shows real-world experience.
Red Flags: "It's deprecated, so it's fine." Relying on the OpenAPI spec as the inventory. Auth attached per router or per route with no global default. Testing only the current API version.
Q61: A shared Redis cache turns into remote code execution through pickle
Level: Principal
Scenario: Several services share one Redis instance for caching. The payments service stores user profiles as pickle.dumps(profile) and reads them back with pickle.loads. Redis has no authentication and is reachable from every pod in the cluster. An attacker exploits an unrelated bug in a low-value marketing service, connects to Redis from there, and overwrites a cached profile key with a crafted pickle. The next time the payments service reads that key, the attacker's code runs inside the payments service, with its database credentials and payment-provider keys.
Impact: Lateral movement from the least important service to the most sensitive one. Full compromise of payments infrastructure.
Root Cause:
- Insecure deserialization (part of A08, Software and Data Integrity Failures):
picklecan execute arbitrary code during loading. It must never be used on data that anyone else can write. The same applies toyaml.loadwith an unsafe loader,marshal,shelve, andjsonpickle. - Treating the cache as trusted: "we wrote it, so we can read it" ignores everyone else who can write it.
- Flat trust inside the network: one shared Redis with no authentication, no per-service ACLs, and no network policy.
Fix:
- Replace
picklewith a data-only format (JSON, MessagePack, Protocol Buffers) and validate the shape on read. - Where integrity matters, sign cached values with an HMAC key only the owning service holds, and reject entries that fail verification.
- Isolate Redis: authentication and per-service ACL users (Redis 6 and later support ACLs) limited to their own key prefixes and commands, TLS, network policies so only owning services can connect, and separate instances for different trust levels.
- Rotate every credential the payments service held, and hunt for persistence.
- Add a SAST rule that flags
pickle.loads,yaml.loadwithout a safe loader, and similar calls.
import hashlib
import hmac
import json
import secrets
CACHE_SIGNING_KEY = secrets.token_bytes(32) # load from a secrets manager; rotate like any key
class TamperedCacheEntry(Exception):
pass
def dumps_signed(value: dict) -> bytes:
"""JSON (data only, no code) plus an HMAC so tampered entries are rejected."""
payload = json.dumps(value, separators=(",", ":"), sort_keys=True).encode()
tag = hmac.new(CACHE_SIGNING_KEY, payload, hashlib.sha256).hexdigest().encode()
return tag + b"." + payload
def loads_signed(blob: bytes) -> dict:
tag, _, payload = blob.partition(b".")
expected = hmac.new(CACHE_SIGNING_KEY, payload, hashlib.sha256).hexdigest().encode()
if not hmac.compare_digest(tag, expected):
raise TamperedCacheEntry("cache entry failed integrity check")
return json.loads(payload)
# VULNERABLE (do not use with data anyone else can write):
# import pickle
# profile = pickle.loads(redis_client.get(f"profile:{user_id}"))
# -> unpickling attacker-controlled bytes can execute arbitrary code
blob = dumps_signed({"user_id": 42, "plan": "pro"})
print(loads_signed(blob)) # {'plan': 'pro', 'user_id': 42}
try:
loads_signed(blob.replace(b'"pro"', b'"enterprise"'))
except TamperedCacheEntry as exc:
print(exc) # cache entry failed integrity check
# Redis ACL (redis.conf / ACL file): each service may only touch its own key prefix
user payments on >use-a-long-random-password ~payments:* +get +set +del +expire
user marketing on >use-another-long-random-password ~marketing:* +get +set +del +expire
user default off
Workflow Diagram:
BEFORE
[marketing svc] --compromised--> [shared Redis, no auth] --crafted pickle--> [payments svc: pickle.loads] --> RCE
AFTER
[marketing svc] --ACL user "marketing", ~marketing:* only--X cannot write payments:* keys
|
NetworkPolicy: only payments pods may reach payments-redis
|
[payments svc] <-- JSON + HMAC verify <-- payments:* keys (tampered entry -> rejected, cache miss)
Interviewer Notes: Principal candidates connect three ideas: deserialization of untrusted data is code execution, internal data stores are not automatically trusted, and blast-radius reduction (per-service credentials and network isolation) is what stops one compromise from becoming many. They also note that signing protects integrity, not confidentiality, so sensitive cached data may additionally need encryption, and that the signing key must not be shared with the services you are defending against.
Red Flags: "Only our services can reach Redis." Replacing pickle with jsonpickle or yaml.load (same problem). Signing with a key every service shares. Fixing the code but leaving Redis unauthenticated and flat.
Q62: Nine months of logs contain session tokens and card numbers, but no record of failed admin access
Level: Senior / Principal
Scenario: While migrating to a new logging vendor, an engineer notices that the request-logging middleware has been writing full request headers and bodies for nine months. Logs contain Authorization headers, session cookies, passwords from the login form and full card numbers from the checkout API. About 300 engineers and two vendors can search these logs. In the same review, the security team finds that failed authorization checks on admin endpoints are not logged at all, so they cannot tell whether anyone has been probing.
Impact:
- Anyone with log access could hijack live sessions or reuse API tokens.
- Card numbers in logs are a serious compliance problem under PCI DSS, which forbids storing that data outside tightly controlled systems.
- Missing security events mean attacks cannot be detected or investigated (A09, Security Logging and Monitoring Failures).
Root Cause: Logging was designed for debugging convenience with a denylist mindset ("log everything, hide what we know is secret") and no tests. Security-relevant events were never defined, so nobody logged them. Log access was broad because logs were considered "operational data".
Fix:
- Stop the leak: deploy an allowlist-based request logger, and add redaction at the log pipeline as a second layer.
- Treat everything logged as compromised: invalidate sessions, rotate API tokens and any credentials that appeared, and force password resets for affected users if passwords were logged.
- Purge: delete the sensitive data from the log store, vendor copies, backups and archives (contractually confirm deletion with vendors). Involve compliance for the card-data exposure.
- Log the right things: authentication successes and failures, authorization failures, admin actions, permission and key changes, and input-validation failures on sensitive endpoints, each with actor, action, target, result, source IP and correlation ID, and without secrets.
- Protect logs as sensitive data: least-privilege access, audit who searches, retention limits, and tamper-evident storage for audit logs.
- Test it: CI tests that send known fake secrets through the logging path and assert they never appear (below).
import logging
import pytest
log = logging.getLogger("api.access")
SENSITIVE_HEADERS = {"authorization", "cookie", "x-api-key"}
LOGGED_BODY_FIELDS = {"order_id", "currency", "amount"} # allowlist, not denylist
def log_request(method: str, path: str, headers: dict[str, str], body: dict) -> None:
safe_headers = {k: ("[REDACTED]" if k.lower() in SENSITIVE_HEADERS else v) for k, v in headers.items()}
safe_body = {k: v for k, v in body.items() if k in LOGGED_BODY_FIELDS}
log.info("request method=%s path=%s headers=%s body=%s", method, path, safe_headers, safe_body)
SECRETS = ["Bearer eyJhbGciOiJSUzI1NiJ9.fake.token", "session=abc123secret", "hunter2", "4111111111111111"]
@pytest.mark.parametrize("secret", SECRETS)
def test_request_logging_never_contains_secrets(caplog, secret):
caplog.set_level(logging.INFO, logger="api.access")
log_request(
"POST",
"/api/checkout",
headers={"Authorization": SECRETS[0], "Cookie": SECRETS[1], "User-Agent": "pytest"},
body={"order_id": "o-1", "amount": 1200, "currency": "EUR", "password": SECRETS[2], "card_number": SECRETS[3]},
)
assert secret not in caplog.text
assert "o-1" in caplog.text # still useful for debugging
import logging
security_log = logging.getLogger("security.audit")
def log_authorization_failure(*, actor_id: str, action: str, resource: str, source_ip: str, request_id: str) -> None:
# Structured, secret-free security event: who tried what, on what, from where, with what result.
security_log.warning(
"authorization denied",
extra={
"event": "authz.denied",
"actor_id": actor_id,
"action": action,
"resource": resource,
"source_ip": source_ip,
"request_id": request_id,
},
)
Workflow Diagram:
Discovery: secrets found in logs
|
+--> STOP: allowlist logger + pipeline redaction (deploy today)
+--> ROTATE: sessions, API tokens, credentials seen in logs
+--> PURGE: log store, vendor copies, backups, archives (+ compliance for card data)
|
v
DEFINE security events: authn ok/fail, authz denied, admin actions, key/role changes
|
v
PROTECT logs: least-privilege access, access auditing, retention, tamper-evident audit store
|
v
DETECT: alerts on authz-denied bursts, admin actions at odd hours, impossible travel
|
v
PREVENT: CI tests with fake secrets; review of new log statements
Interviewer Notes: A09 has two sides and strong candidates cover both: logging the wrong things (secrets, card data, personal data) and not logging the right things (security events needed for detection and forensics). They treat leaked credentials in logs as a breach requiring rotation, not just deletion, and they think about who can read logs. Principal candidates add data classification for log fields, vendor contracts covering deletion, and alerting built on the new security events.
Red Flags: Deleting the logs without rotating the exposed tokens. A denylist of "known secret field names" as the only control. Logging full request bodies "temporarily" in production. No security events, or security events that themselves contain passwords or tokens.