Fix the constant time check for API keys

Review the AI's codeMedium15 min

Your task

Your API compares the key a caller sends with the key it expects. The first draft called subtle.SecureCompare, a Go function that does not exist, and returned early when the two lengths differed. That early return tells an attacker how long the real key is.

An assistant wrote constant_time_key_match(provided, expected) to replace it. It never returns early, so the time it takes does not depend on how much of the key matched. It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • provided: the key the caller sent.
  • expected: the key your server expects.
  • Return 1 when they match and 0 when they do not, the way Go's real subtle.ConstantTimeCompare does.

Rules the tests check:

  • They match only when provided and expected are exactly the same string: same length, same characters, same case. Spaces count.
  • Two empty strings match.

Examples

constant_time_key_match(provided: str, expected: str) -> int
Example 1
Inputconstant_time_key_match("sk_live_abc123", "sk_live_abc123")
Output1
Example 2
Inputconstant_time_key_match("sk_live_abc124", "sk_live_abc123")
Output0
Example 3
Inputconstant_time_key_match("sk", "sk_live_abc123")
Output0