Module api_key_validation

Module api_key_validation 

Source
Expand description

Secure API Key Validation with Constant-Time Comparison

This module provides timing-attack resistant API key validation using:

  • blake3 for fast cryptographic hashing
  • subtle for constant-time comparison

§Security Properties

  • Timing Attack Resistance: Uses constant-time comparison to prevent character-by-character guessing of API keys through timing side-channels.
  • Pre-hashing: Hashes keys before comparison to ensure comparison time is independent of actual key values.
  • Length Independence: Comparison time is independent of key length due to fixed hash size.

§Attack Scenario Prevented

Without constant-time comparison, an attacker could measure response times:

Attempt: "a..." → 0.1ms (wrong first char, fails fast)
Attempt: "s..." → 0.2ms (correct first char, continues comparison)
Attempt: "sk..." → 0.3ms (correct first two chars, continues longer)

With constant-time comparison, all attempts take the same time regardless of correctness.

§Usage

use turbomcp_auth::api_key_validation::validate_api_key;

let provided_key = "sk_live_abc123";
let expected_key = "sk_live_abc123";

if validate_api_key(provided_key, expected_key) {
    // Authenticated
} else {
    // Invalid key
}

§Implementation Notes

  • Uses blake3 instead of SHA-256 for performance (10x faster, still cryptographically secure)
  • Hash size: 32 bytes (256 bits)
  • Comparison time: ~1-2 nanoseconds (constant regardless of input)

Functions§

validate_api_key
Validate an API key using constant-time comparison
validate_api_key_multiple
Validate an API key against multiple possible keys (constant-time)