KatInterview

Secure Password Verification in Express Without Blocking

BehavioralModel answer
MediumModel answerBehavioralnode.jsexpresssecurity

Last updated

Fix a Node.js authentication endpoint: validate input, compare passwords asynchronously, return safe errors, and prevent event-loop blocking.

You are reviewing a Node.js Express authentication endpoint that verifies user credentials. The endpoint accepts a username and password via POST, retrieves the user record from a database, compares the provided password against a stored bcrypt hash, and responds with success or failure.

The current implementation has several problems:

  • No input validation
  • Missing error handling
  • Synchronous password comparison that blocks the event loop
  • Inappropriate exposure of internal errors

Your task is to describe a corrected implementation that:

  1. Validates and sanitizes input appropriately
  2. Uses asynchronous bcrypt comparison to avoid blocking
  3. Returns correct HTTP status codes
  4. Handles errors safely without leaking sensitive information
  5. Ensures only one response is sent per request

Requirements

  • Authentication succeeds only when both username exists and password matches
  • Return JSON responses for all outcomes
  • Session or token creation happens elsewhere; your endpoint only verifies credentials
  • Do not log passwords or expose database internals to clients
  • You may define any reasonable database adapter interface for illustration

Discussion Points

Consider and explain:

  • What validation rules should apply to username and password inputs?
  • How should you distinguish malformed requests from valid requests with incorrect credentials?
  • What is the difference between avoiding event-loop blocking and controlling resource cost under load?
  • What questions would you ask before implementing this in a real system?

Hints

Hint 1

Validate input types and length limits before any database or crypto operations

Hint 2

Use bcrypt.compare (async) not compareSync; return a generic message for any credential mismatch

Hint 3

Consider rate limiting separately from async operations—bcrypt is non-blocking but still CPU-intensive