Ace Security Interviews: Threat Model Your API
You just nailed the system design round, sketching out a scalable, distributed microservice handling millions of requests per second. The interviewer nods, impressed. Then comes the curveball: "Okay, great. Now, how would you secure this API? Walk me through a threat model for that new user registration endpoint." This isn't theoretical B.S. anymore; this is where most security interviews either shine or crash hard. Many engineers can build; far fewer can truly secure. You'll differentiate yourself by actually thinking like an attacker, not just rattling off OWASP Top 10.
Let's be clear: a security interview isn't about memorizing every CVE. It's about demonstrating a methodical, attacker-centric mindset. When they ask you to threat model an API, they want to see your process, your assumptions, and your ability to articulate risks and countermeasures. This isn't just about passing an interview; it's how you build secure systems in the real world. I've sat on both sides of that table, and trust me, the candidates who excel here aren't just reciting facts—they're thinking.
The Core Concept: D.R.E.A.D. vs. STRIDE
Forget acronym overload for a second. The goal of any threat model is to identify potential vulnerabilities and design mitigations before a system goes live. In interviews, you'll often hear "STRIDE" (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege) or "DREAD" (Damage, Reproducibility, Exploitability, Affected Users, Discoverability). While STRIDE is a fantastic framework for categorizing threats, DREAD is more about quantifying risk once you've found a threat. For an API threat model in an interview setting, you're primarily using STRIDE as a lens to find the threats. You're not going to spend 15 minutes calculating DREAD scores. Your focus needs to be on walking through the API's data flow, identifying assets, and then systematically applying the STRIDE categories to unearth potential issues.
Think about that user registration endpoint again. What data flows into it? What data flows out? What processing happens in between? Who are the actors? What are their trust boundaries? You need to mentally sketch this out, even if you don't draw it. This is your foundation.
Breaking Down an API Endpoint: An Example
Let's stick with that user registration API: POST /api/v1/register.
1. Define the Scope and Assets:
- Endpoint:
/api/v1/register - Method: POST
- Request Body:
{"username": "string", "email": "string", "password": "string"}(maybefirst_name,last_nametoo) - Response Body:
{"message": "Registration successful", "user_id": "uuid"}or{"error": "string"} - Actors: Unauthenticated User, Authenticated User (post-registration, if applicable), API Gateway, Backend Registration Service, Database, Email Service (for verification).
- Data in Transit: User PII (username, email, password), IP Address.
- Data at Rest: User credentials (hashed), email, user ID in database.
- Trust Boundaries: Client (browser/mobile app) to API Gateway, API Gateway to Backend Service, Backend Service to Database, Backend Service to Email Service. Each boundary is a potential point of attack.
This initial breakdown isn't rocket science, but it ensures you and the interviewer are on the same page. It also helps you visualize where data could be compromised.
Applying STRIDE: A Systematic Attack
Now, go through each STRIDE category and ask, "How could an attacker exploit this aspect of the system for this particular threat?"
Spoofing (Identity)
- Threat: An attacker pretends to be a legitimate user or a legitimate service.
- Scenario:
- User Spoofing: Can someone register with a username or email that already exists? What if they try to register with an email from a legitimate domain they don't own (e.g.,
ceo@yourcompany.com)? This isn't directly spoofing another user's identity, but it can lead to social engineering or confusion. - Service Spoofing: Could an attacker trick your service into thinking they are the legitimate email verification service, or vice versa? This could happen if your service-to-service communication isn't properly authenticated.
- User Spoofing: Can someone register with a username or email that already exists? What if they try to register with an email from a legitimate domain they don't own (e.g.,
- Mitigation:
- Unique Constraints: Enforce unique usernames and emails at the database level.
- Email Verification: Send a verification link to the registered email address. This confirms ownership.
- Strong Authentication: For internal service-to-service calls, use mTLS (mutual TLS), API keys with strict ACLs, or JWTs signed by an internal identity provider.
Tampering (Data Integrity)
- Threat: An attacker modifies data in transit or at rest.
- Scenario:
- Request Tampering: Can an attacker modify the
username,email, orpasswordfields in the HTTP request mid-flight? What if they inject SQL or NoSQL injection payloads into these fields? - Password Tampering: Can an attacker intercept and modify the password before it reaches the server, perhaps to set a known weak password?
- Database Tampering: Once registered, could an attacker directly tamper with the user record in the database if there's a vulnerability in the backend service?
- Request Tampering: Can an attacker modify the
- Mitigation:
- HTTPS (TLS): Crucial for all communication. This prevents most in-transit modification.
- Input Validation: Strict server-side validation for all input fields (e.g., email format, password strength, username length, character sets). Don't trust client-side validation. Use libraries like
JoiorPydantic. - SQL/NoSQL Injection Prevention: Parameterized queries, ORMs (when used correctly), input sanitization.
- Strong Password Hashing: Use algorithms like bcrypt, scrypt, or Argon2 with strong salts. Never store plaintext passwords.
Repudiation (Non-Repudiation)
- Threat: An attacker (or legitimate user) denies performing an action.
- Scenario:
- User Denies Registration: Can a user claim they never registered, even after doing so? This is often less critical for a registration endpoint itself, but important for sensitive actions like financial transactions. However, if a malicious account is created, you need to prove who did it.
- Mitigation:
- Comprehensive Logging: Log all successful and failed registration attempts, including source IP address, timestamp, and relevant identifiers (e.g., email address). Store these logs securely and immutably.
- Audit Trails: Ensure your database or services maintain an audit trail for critical actions.
Information Disclosure (Confidentiality)
- Threat: Sensitive information is exposed to unauthorized individuals.
- Scenario:
- Error Messages: Do error messages reveal too much internal server information (stack traces, database details)?
- User Enumeration: Does the API tell an attacker if a username or email already exists (e.g., "Username already taken" vs. a generic "Invalid credentials")? This allows attackers to build lists of valid users.
- Password Echoing: Does the API ever return the password in a response, even hashed?
- Leaked PII: If the database is compromised, how is sensitive user data protected?
- Mitigation:
- Generic Error Messages: Return vague error messages like "Registration failed" unless specific feedback is absolutely necessary.
- Timing Attacks & Enumeration Prevention: Implement a consistent response time for both valid and invalid credentials. For registration, return a generic "If an account exists for that email, a verification link has been sent" message for password resets, and for registration, "Registration successful" whether the email already existed or not (but only create the account if it's new). This makes enumeration harder.
- Never Return Passwords: Even hashed passwords shouldn't be returned to the client.
- Data Encryption at Rest: Encrypt sensitive columns in the database (e.g., if you store PII beyond basic login). Use disk encryption.
- Access Control: Strict access controls on who can view production logs and databases.
Denial of Service (Availability)
- Threat: An attacker prevents legitimate users from accessing the service.
- Scenario:
- Brute-Force Registration: An attacker repeatedly attempts to register, overwhelming the database or email service.
- Resource Exhaustion: An attacker sends very large request bodies, or requests that trigger expensive database operations, consuming CPU/memory.
- Email Bombing: An attacker triggers thousands of email verifications, impacting your email service's reputation or cost.
- Mitigation:
- Rate Limiting: Implement API Gateway or application-level rate limiting (e.g.,
Xrequests per minute per IP address). Use tools like Nginx, API Gateways, or libraries likeexpress-rate-limit. - CAPTCHA/reCAPTCHA: For registration endpoints, use CAPTCHA to differentiate humans from bots.
- Resource Quotas: Set limits on request body size.
- Asynchronous Processing: If email sending is a bottleneck, offload it to a message queue (e.g., SQS, Kafka) to prevent it from blocking the main registration flow.
- Load Balancing & Auto-Scaling: Distribute traffic and scale up resources automatically to handle spikes.
- Rate Limiting: Implement API Gateway or application-level rate limiting (e.g.,
Elevation of Privilege (Authorization)
- Threat: An attacker gains higher privileges than intended.
- Scenario:
- Horizontal Privilege Escalation: Can one user register in a way that gives them access to another user's account? (Less common for registration itself, more for subsequent actions).
- Vertical Privilege Escalation: Can an attacker register an account and somehow gain administrative privileges? Perhaps through a malformed request body that sets an
is_admin: trueflag.
- Mitigation:
- Strict Authorization: Ensure the registration endpoint only performs registration. It should not accept or process any
roleorprivilegefields from the client. These should be set internally by the system based on business logic. - Least Privilege: The service account running the registration service should only have the database permissions it absolutely needs (e.g.,
INSERTinto the users table, notUPDATEorDELETEon arbitrary records).
- Strict Authorization: Ensure the registration endpoint only performs registration. It should not accept or process any
Beyond STRIDE: Practical Interview Tactics
Once you've walked through STRIDE, you're not done. A senior engineer doesn't just list problems; they prioritize and suggest next steps.
1. Prioritization: "Given these threats, I'd say the most critical for a new registration endpoint are Information Disclosure (user enumeration) and Tampering (password hashing, input validation), followed closely by Denial of Service (rate limiting). These are foundational to user trust and system stability."
2. Attack Trees/Kill Chains (Briefly): You don't need to draw a full attack tree, but showing you understand how multiple vulnerabilities chain together is powerful. "An attacker might first use user enumeration to gather valid emails, then use a timing attack on the login endpoint to find weak passwords, and finally attempt brute-force login. Our strong password policy and rate limiting on login would mitigate this."
3. Defensive Layers: Talk about defense in depth. "No single control is perfect. We'd have layers: network-level controls (firewalls, WAF), API Gateway for 인증 and rate limiting, application-level input validation and secure coding practices, and database-level encryption and access controls."
4. Continuous Security: "Threat modeling isn't a one-and-done. We'd revisit this after major feature changes, perform regular penetration testing and vulnerability scanning, and integrate security into our CI/CD pipeline with static analysis tools (SAST) and dynamic analysis (DAST)."
5. Tools and Technologies: Don't just say "use security tools." Name specifics. * WAF: Cloudflare, AWS WAF, Akamai. * SAST: SonarQube, Snyk, Checkmarx. * DAST: OWASP ZAP, Burp Suite. * Secrets Management: HashiCorp Vault, AWS Secrets Manager, Azure Key Vault. * Logging/Monitoring: ELK stack, Splunk, Datadog.
The Caveat: It Depends on Your Context
Now, honestly, how much detail you go into depends entirely on the company, the role, and the time allotted. If you're interviewing for a dedicated security engineer role, they'll expect deep dives into every point. If it's a general backend engineer role, they might be happy with a solid STRIDE walkthrough and a few key mitigations. Always gauge the interviewer's reaction and adjust your depth. Don't spend 10 minutes on email verification if they're clearly looking for your thoughts on database encryption.
Also, the type of API matters. A public, unauthenticated registration endpoint has different threats than an internal, authenticated microservice endpoint. Adjust your focus accordingly. For instance, an internal service might focus more on mTLS and granular access control (Elevation of Privilege, Spoofing between services), while an external API emphasizes rate limiting and input validation (DoS, Tampering).
Common Mistakes to Avoid
- Rattling off buzzwords without explanation: "We'll use zero trust and blockchain for security!" If you can't explain how and why it applies, don't say it.
- Focusing only on code vulnerabilities: Security is broader than just XSS and SQLi. Think about architecture, operations, and people.
- Ignoring the "why": Always explain why a mitigation works against a specific threat. "We use HTTPS" is good. "We use HTTPS to prevent in-transit tampering and information disclosure by encrypting the communication channel" is better.
- Not asking clarifying questions: If you're unsure about the system's architecture (e.g., "Is there an API Gateway? Is this a microservice or monolith?"), ask! It shows you're thinking critically.
- Being rigid: Be prepared to pivot if the interviewer guides you in a different direction. It's a conversation, not a monologue.
Ultimately, acing this part of the interview isn't about having all the answers, it's about demonstrating a structured, critical thinking process when faced with a security challenge. You're showing them you can identify problems, articulate their impact, and propose sensible, layered solutions. That's a skill every senior engineer needs.
Ready to Ace Your Next Interview?
Practice with AI-powered mock interviews tailored to your target role and company. Start Practicing for Free | Explore Interview Prep
