HIGH api key exposurehanamiruby

Api Key Exposure in Hanami (Ruby)

Api Key Exposure in Hanami with Ruby — how this specific combination creates or exposes the vulnerability

Hanami is a Ruby web framework that emphasizes explicit architecture and modular design. When developers use Hanami with Ruby to build services that rely on API keys—for example, to call external payment gateways, cloud providers, or third‑party data APIs—the framework does not automatically protect those keys. If keys are embedded in Ruby source files, initializer configuration, or environment files that are committed to version control, they can be exposed through repository leaks, misconfigured deployments, or accidental logging.

During a middleBrick scan of an unauthenticated endpoint that uses Hanami and Ruby, the API Security checks examine how API keys are handled. The scan can detect keys exposed in responses (e.g., error messages containing stack traces or configuration snippets), in OpenAPI/Swagger specs where keys appear as examples or default values, or in runtime behaviors that indicate missing authorization checks. Because Hanami applications often compose multiple services via explicit dependencies, keys may travel across layers—controllers, services, and repositories—creating multiple opportunities for exposure if not consistently guarded.

Specific risk patterns include storing API keys as plain strings in config/initializers or environment variables that are logged by Ruby’s standard libraries; failing to filter sensitive parameters in Hanami actions, which can cause keys to appear in logs or error output; and using keys in client objects that are inadvertently serialized in HTTP responses or debug output. The OpenAPI analysis phase of a middleBrick scan can reveal $ref structures and examples that inadvertently contain key values, while the Runtime findings can highlight endpoints that return sensitive data without proper authorization, effectively mapping the exposure to the OWASP API Security Top 10 and relevant compliance frameworks.

Ruby-Specific Remediation in Hanami — concrete code fixes

To mitigate API key exposure in Hanami with Ruby, apply consistent patterns that keep keys out of code and responses, and enforce strict access controls. Use environment variables loaded through secure mechanisms, avoid embedding keys in source code, and ensure Hanami actions filter sensitive parameters and do not propagate keys into logs or error outputs.

Example: Load API keys from environment variables using ENV and a configuration object, and reference them in service objects without exposing them in responses.

module MyApp
  class ApiClient
    def initialize
      @api_key = ENV.fetch("EXTERNAL_API_KEY")
    end

    def call_external_service(payload)
      # Use the key only within secure outbound calls
      request = MyApp::Request.new("https://api.external.com/do", headers: { "Authorization" => "Bearer #{@api_key}" })
      request.post(payload)
    end
  end
end

Example: In a Hanami action, ensure sensitive parameters are not included in logs or views, and avoid passing raw keys to presenters or serializers.

# app/actions/api/proxy.rb
module Api
  module Proxy
    class ProxyAction
      include Hanami::Action

      def handle(params)
        # Validate and use the key server-side; do not forward it to the client
        key_id = params[:key_id]
        record = MyApp::Repository::Keys.find(key_id)
        raise Hanami::Action::UnauthorizedError unless record&.active?

        # Perform the external call using a service that reads the key from secure storage
        result = MyApp::Services::ExternalCaller.new(record.id).call
        { result: result }
      end
    end
  end
end

Example: Configure logging to filter sensitive data and ensure that Ruby backtraces do not leak keys in development or production error pages.

# config/initializers/filter_parameter_logging.rb
if defined?(Hanami::Logger)
  Hanami::Logger.configure do |config|
    config.filter = [:api_key, :secret, :token]
  end
end

Additionally, use the middleBrick CLI to validate that your endpoints do not expose keys in responses or specs: middlebrick scan <url>. For teams needing automated oversight across multiple services, the Pro plan provides continuous monitoring and CI/CD integration to catch regressions early. If you use AI coding assistants, the MCP Server allows you to scan APIs directly from your IDE, reinforcing secure practices during development.

Frequently Asked Questions

Can a Hanami initializer accidentally expose API keys?
Yes. If a Hanami initializer loads API keys from environment variables but includes them in logs, error pages, or default OpenAPI examples, keys can be exposed. Always use ENV.fetch, avoid embedding keys in source, and filter sensitive parameters in logging configuration.
How does middleBrick detect API key exposure in Hanami apps?
middleBrick scans the unauthenticated attack surface and analyzes OpenAPI/Swagger specs and runtime behavior. It can identify keys in examples, detect missing authorization on endpoints that return sensitive data, and flag patterns where keys could leak through logs or error outputs.