Module: Legion::LLM::API::Auth
- Extended by:
- Legion::Logging::Helper
- Defined in:
- lib/legion/llm/api/auth.rb
Class Method Summary collapse
-
.anthropic_client?(env) ⇒ Boolean
Detects whether the incoming request is from an Anthropic SDK client.
- .registered(app) ⇒ Object
Class Method Details
.anthropic_client?(env) ⇒ Boolean
Detects whether the incoming request is from an Anthropic SDK client. Anthropic clients set anthropic-version header, or use x-api-key without a Bearer token.
71 72 73 74 75 |
# File 'lib/legion/llm/api/auth.rb', line 71 def self.anthropic_client?(env) return true if env['HTTP_ANTHROPIC_VERSION'] env['HTTP_X_API_KEY'] && !env['HTTP_AUTHORIZATION']&.match?(/\ABearer\s+/i) end |
.registered(app) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/legion/llm/api/auth.rb', line 11 def self.registered(app) log.debug('[llm][api][auth] registering /v1/* and /api/llm/inference/v1/* before filters') auth_check = proc do log.debug("[llm][api][auth] before filter action=check path=#{request.path_info}") next unless auth_enabled? token = extract_token(request) log.debug("[llm][api][auth] action=validate token_present=#{!token.nil?}") unless valid_token?(token) log.warn("[llm][api][auth] action=rejected reason=invalid_token path=#{request.path_info}") error_body = if Auth.anthropic_client?(request.env) { type: 'error', error: { type: 'authentication_error', message: 'Invalid API key' } } else { error: { message: 'Invalid API key', type: 'authentication_error' } } end halt 401, { 'Content-Type' => 'application/json' }, Legion::JSON.dump(error_body) end log.debug("[llm][api][auth] action=authorized path=#{request.path_info}") end app.before('/api/llm/inference/v1/*', &auth_check) app.before('/v1/*', &auth_check) app.helpers do define_method(:auth_enabled?) do Legion::LLM::Settings.value(:api, :auth, :enabled) == true end define_method(:extract_token) do |req| auth_header = req.env['HTTP_AUTHORIZATION'] if auth_header&.match?(/\ABearer\s+/i) log.debug('[llm][api][auth] token_source=bearer_header') return auth_header.sub(/\ABearer\s+/i, '') end key = req.env['HTTP_X_API_KEY'] log.debug("[llm][api][auth] token_source=x_api_key present=#{!key.nil?}") key end define_method(:valid_token?) do |token| return true unless auth_enabled? return false if token.nil? || token.empty? keys = Legion::LLM::Settings.value(:api, :auth, :api_keys, default: []) keys.include?(token) end end log.debug('[llm][api][auth] /v1/* and /api/llm/inference/v1/* before filters registered') rescue StandardError => e handle_exception(e, level: :error, handled: false, operation: 'llm.api.auth.register') end |