HIGH api key exposurehanamiapi keys

Api Key Exposure in Hanami with Api Keys

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

Hanami is a Ruby web framework that encourages modular design by organizing applications as collections of reusable apps and services. When developers use the hanami gem together with the api_keys gem to manage service-to-service credentials, they introduce a specific risk pattern where API keys are handled in ways that can lead to exposure. The vulnerability arises when keys are embedded in source code, initializer files, or environment configurations that are inadvertently committed to version control or exposed through logs and error messages.

During a black-box scan, middleBrick tests the unauthenticated attack surface of a Hanami application and checks for indicators such as key leakage in HTTP responses, debug pages, or open endpoints that return configuration data. If a Hanami app exposes an endpoint that renders environment variables or gem configuration, keys stored in api_keys may be returned in plaintext. The framework’s convention of loading many configuration files at boot time means that an overlooked initializer can expose sensitive material through seemingly harmless routes. For example, an endpoint like /debug/config that dumps settings for troubleshooting can leak keys if it does not strip sensitive values before serialization.

Another common pattern involves the api_keys gem reading credentials from files or environment variables and then passing them to external services. If the Hanami app does not restrict which hosts can be called, an attacker might trigger outbound requests from the server through SSRF, causing keys to be sent to malicious endpoints or logged in remote service access logs. middleBrick’s checks for Data Exposure and SSRF validate whether keys appear in responses or outbound traffic, testing with patterns that match common key formats such as AKIA[0-9A-Z]{16}. Since the scan runs without authentication, it can detect whether keys are reachable through public routes or reflected in error payloads without requiring credentials.

Logging practices in Hanami applications can also contribute to exposure. When the api_keys gem is used inside service objects or adapters, developers might log request parameters or response headers for debugging. If those logs include the full configuration hash passed to the gem, keys can end up in centralized logging systems where they are accessible to more users than necessary. middleBrick’s Data Exposure checks look for sensitive values in sample responses and inspect application behavior around error handling to determine whether keys are surfaced in stack traces or diagnostic pages.

The combination of framework conventions and gem behavior means that an API key intended for internal use can become a widespread secret. Because the hanami framework does not inherently redact sensitive configuration, the responsibility falls on the developer to ensure that keys are not serialized in views, passed to untrusted subprocesses, or included in repository history. middleBrick’s cross-referencing of OpenAPI specs with runtime findings helps highlight discrepancies where documentation claims keys are managed securely, but runtime endpoints reveal them.

To summarize, the risk with Hanami and api_keys is not a flaw in either project, but a result of how keys are stored, accessed, and logged. Without runtime validation, developers may assume that environment isolation is sufficient, while endpoints, logs, and error handlers can still act as leakage channels. middleBrick identifies these patterns by testing the live application surface and comparing findings against best practices for secret management and exposure prevention.

Api Keys-Specific Remediation in Hanami — concrete code fixes

Remediation focuses on how the api_keys gem is integrated into a Hanami application. The goal is to prevent keys from appearing in code, logs, or responses while ensuring that they are only used in authorized network contexts. Below are concrete changes you can apply to reduce exposure.

1. Keep keys out of source code

Instead of hardcoding keys in initializers, load them exclusively from environment variables at runtime. This avoids committing secrets to version control.

# config/initializers/api_keys.rb
require "api_keys"

ApiKeys.configure do |config|
  config.project_key = ENV.fetch("PROJECT_API_KEY")
  config.base_url    = ENV.fetch("PROJECT_API_HOST")
end

2. Restrict logging of sensitive values

Ensure that log filters remove keys from any structured output. Hanami allows custom log formatting; use it to scrub known key fields.

# config/initializers/filter_parameter_logging.rb
Hanami.configure do |config|
  config.filter_parameters << :project_api_key
  config.filter_parameters << :api_key_token
end

3. Validate outbound hosts for the api_keys gem

If the gem makes HTTP calls, limit destinations to known endpoints only. This prevents SSRF-assisted key exfiltration.

# app/services/restricted_connector.rb
require "net/http"

module RestrictedConnector
  def self.get(endpoint)
    uri = URI(endpoint)
    raise "Host not allowed" unless uri.host == "api.trusted-service.com"

    req = Net::HTTP::Get.new(uri)
    req["Authorization"] = "Bearer #{ENV.fetch("PROJECT_API_KEY")}"

    res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
      http.request(req)
    end
    res.body
  end
end

4. Remove keys from debug endpoints

If you maintain internal endpoints for troubleshooting, explicitly exclude sensitive configuration before rendering.

# app/web/controllers/debug_controller.rb
class DebugController < Hanami::Action
  def show
    public_info = {
      version: AppConfiguration.version,
      environment: Hanami.env
    }
    # Exclude keys before serialization
    render json: public_info
  end
end

5. Rotate keys and audit usage

Even with code changes, previously exposed keys should be rotated. Use the api_keys configuration to point to new values and verify that no old references remain in deployment artifacts.

6. Use middleware to intercept accidental exposure

Add a lightweight middleware that scans responses for key-like patterns and blocks the request in development.

# lib/middleware/api_key_guard.rb
class ApiKeyGuard
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, body = @app.call(env)

    if body.to_s.match?(/AKIA[0-9A-Z]{16}/)
      raise "Potential API key leaked in response"
    end

    [status, headers, body]
  end
end

# config/application.rb
use ApiKeyGuard

These steps address the specific interaction between Hanami and the api_keys gem. By controlling configuration sources, tightening logging, validating network destinations, and sanitizing responses, you reduce the likelihood of keys being exposed through the application surface that middleBrick evaluates during scanning.

Frequently Asked Questions

Can middleBrick remove or rotate exposed API keys in Hanami?
middleBrick detects and reports API key exposure but does not remove, rotate, or modify any secrets. You must rotate keys through your own credential management process and apply code fixes in Hanami.
Does scanning a Hanami app with api_keys require authentication in middleBrick?
No, middleBrick scans the unauthenticated attack surface by default. Authentication is optional and can be provided if you want to test additional authenticated endpoints, but the core checks run without credentials.