validate_api_key

Function validate_api_key 

Source
pub fn validate_api_key(provided: &str, expected: &str) -> bool
Expand description

Validate an API key using constant-time comparison

This function is timing-attack resistant. The comparison time is constant regardless of:

  • Which characters are correct
  • Where the mismatch occurs
  • The length of the keys (both are hashed to 32 bytes)

§Security Guarantees

  • Constant Time: Uses subtle::ConstantTimeEq for timing-safe comparison
  • Pre-hashing: Both keys are hashed before comparison
  • No Early Exit: Comparison continues even after finding a mismatch

§Performance

  • Hashing: ~50-100ns per key (BLAKE3 is very fast)
  • Comparison: ~1-2ns (constant time)
  • Total: ~100-200ns per validation

§Example

use turbomcp_auth::api_key_validation::validate_api_key;

let provided = "sk_live_correct_key";
let expected = "sk_live_correct_key";

assert!(validate_api_key(provided, expected));

let wrong_key = "sk_live_wrong_key";
assert!(!validate_api_key(wrong_key, expected));