KatInterview

Build a Single-Use Password Reset Token Manager

Data Structure DesignModel answer
MediumModel answerData Structure Designstate-machinehash-mapauthentication

Last updated

Design an in-memory service that issues reset tokens, enforces expiry and a failed-attempt cap, rejects reused passwords, and makes each token usable only once.

Reset Token Manager

You are building the core of an account-recovery feature. The component hands out short-lived reset tokens, checks them when a user tries to choose a new password, and shuts down tokens that are abused or stale.

Implement a class with this interface:

class PasswordResetService:
    def __init__(self, token_ttl: int, max_attempts: int):
        """
        token_ttl: how many seconds a token stays usable after it is issued.
        max_attempts: how many failed verifications a single token may absorb.
        """

    def register_user(self, user_id: str, password_hash: str) -> None:
        """Create a user with a starting password hash."""

    def request_reset(self, user_id: str, token: str, timestamp: int) -> bool:
        """
        Issue `token` for `user_id` at `timestamp`.
        Returns False if the user is unknown.
        Any earlier token for this user is discarded and replaced.
        Returns True otherwise.
        """

    def verify_and_reset(self, user_id: str, token: str,
                         new_password_hash: str, timestamp: int) -> bool:
        """
        Try to change the user's password using `token`.
        Returns True only if the password was changed.
        """

Rules

  1. Expiry. A token issued at time t is usable for any timestamp with t <= timestamp <= t + token_ttl. A verification at a later time fails and also destroys the token.
  2. Attempt cap. Every verification against a live token that does not succeed adds one to that token's failure count. When the count reaches max_attempts, the token is revoked at once, so later calls fail even with the correct token.
  3. One use. After a successful reset the token is consumed and cannot be used again.
  4. No password reuse. If new_password_hash equals the user's current hash, the call fails and counts as a failed attempt.
  5. Unknown users. Any call naming a user that does not exist returns False and must not raise.

A wrong token counts as a failed attempt (rule 2), as does a correct token paired with an unchanged password (rule 4). A call made when the user has no live token (never requested, expired, consumed, or revoked) just returns False.

Example

svc = PasswordResetService(token_ttl=300, max_attempts=3)
svc.register_user("alice", "h_old")

assert svc.request_reset("alice", "T1", 100) is True
assert svc.verify_and_reset("alice", "BAD", "h_new", 120) is False   # failure 1
assert svc.verify_and_reset("alice", "T1", "h_old", 130) is False    # failure 2 (same password)
assert svc.verify_and_reset("alice", "T1", "h_new", 140) is True     # success, token consumed
assert svc.verify_and_reset("alice", "T1", "h_other", 150) is False  # token already used

What to deliver

Write the class, explain the order in which you evaluate the checks and why, state the complexity, and list the edge cases you handled. Be ready to discuss how you would harden it against timing attacks and run it across multiple servers.

Hints

Hint 1

At most one token can be live per user, so a per-user record holding the token, its issue time and its failure count is enough. Replacing the record on a new request naturally resets the count.

Hint 2

Evaluate checks in a fixed order and return at the first failure: user exists, live token exists, not expired, token matches, password differs. Think about why expiry must come before comparing the token.

Hint 3

Implement revocation and consumption by deleting the record. Then 'no live token' becomes the single rejection path for expired, exhausted, and already-used tokens.