Module: TalkToYourApp::Auth::ApiKey

Defined in:
lib/talk_to_your_app/auth/api_key.rb

Overview

Validates a Bearer token against the configured named API keys. The key’s name becomes the logged principal. Comparison is constant-time once lengths match (a length mismatch short-circuits, which is acceptable: it leaks only the key length, not its contents).

Class Method Summary collapse

Class Method Details

.principal_for(token, api_keys) ⇒ Object

Returns the principal name for a matching token, or nil.



15
16
17
18
19
20
# File 'lib/talk_to_your_app/auth/api_key.rb', line 15

def principal_for(token, api_keys)
  return nil if token.nil? || token.empty? || api_keys.nil? || api_keys.empty?

  match = api_keys.find { |_name, key| secure_compare(token, key.to_s) }
  match&.first&.to_s
end

.secure_compare(given, expected) ⇒ Object



22
23
24
25
26
# File 'lib/talk_to_your_app/auth/api_key.rb', line 22

def secure_compare(given, expected)
  return false unless given.bytesize == expected.bytesize

  OpenSSL.fixed_length_secure_compare(given, expected)
end