Skip to Content
DocumentationRuntime BackendRuby on Rails (Ruby)

Ruby on Rails

Per integrare ProxyTracer in un'applicazione Rails con la massima efficienza, bypassiamo completamente il livello dei controller e costruiamo un middleware Rack personalizzato. Questo intercetta la richiesta HTTP grezza prima che entri nel router di Rails.

Il Middleware Rack

Questo middleware sfrutta l'oggetto nativo Rack::Request per estrarre in sicurezza l'IP (gestendo automaticamente gli header falsificati) e usa la libreria standard Net::HTTP di Ruby per imporre un timeout rigoroso.

require 'net/http' require 'json' class ProxyTracerMiddleware def initialize(app) @app = app @api_key = ENV['PROXYTRACER_API_KEY'] end def call(env) # 1. Estrai l'IP (Rack sanitizza automaticamente X-Forwarded-For) request = Rack::Request.new(env) ip = request.ip # Salta lo sviluppo locale if ip && !['127.0.0.1', '::1'].include?(ip) begin uri = URI("https://api.proxytracer.com/v1/check/#{ip}") req = Net::HTTP::Get.new(uri) req['Authorization'] = "Bearer #{@api_key}" # 2. Interroga l'API ProxyTracer con un timeout rigoroso di 500ms response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 0.5) do |http| http.request(req) end if response.is_a?(Net::HTTPSuccess) data = JSON.parse(response.body) # 3. Interrompi immediatamente la connessione se viene rilevato un proxy if data['proxy'] == true return [ 403, { 'Content-Type' => 'application/json' }, ['{"error": "Access Denied: VPN or Proxy detected."}'] ] end end rescue StandardError => e # Fail open: registra l'errore e consenti alla richiesta di procedere Rails.logger.error("ProxyTracer validation failed: #{e.message}") end end # 4. Il traffico è pulito, procedi lungo lo stack Rack fino al router Rails @app.call(env) end end

Configurazione:

Per attivare la protezione globalmente, inserisci il middleware nel tuo stack dell'applicazione all'interno di config/application.rb:

module YourApp class Application < Rails::Application # ... # Inseriscilo in alto nello stack per respingere tempestivamente il traffico malevolo config.middleware.insert_before Rack::Sendfile, ProxyTracerMiddleware # ... end end
Ultimo aggiornamento il