Fix the constant time check for API keys
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.ConstantTimeComparedoes.
Rules the tests check:
- They match only when
providedandexpectedare 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) -> intExample 1
Input
constant_time_key_match("sk_live_abc123", "sk_live_abc123")Output
1Example 2
Input
constant_time_key_match("sk_live_abc124", "sk_live_abc123")Output
0Example 3
Input
constant_time_key_match("sk", "sk_live_abc123")Output
0