HIGH beast attackhanamiapi keys

Beast Attack in Hanami with Api Keys

Beast Attack in Hanami with Api Keys — how this specific combination creates or exposes the vulnerability

A Beast Attack in Hanami that involves API keys typically arises when API keys are accepted via query parameters or non‑standard headers and then used directly in authorization logic without strict validation and scope checks. Hanami applications that route requests through a gateway or middleware may inadvertently pass these keys into internal service calls, creating a path where an attacker can manipulate the key format or reuse a key across endpoints. Because Hanami encourages explicit, domain‑driven design, misconfigured policy objects or overly permissive route constraints can expose key handling to tampering, enabling account impersonation or privilege escalation.

In a black‑box scan, middleBrick tests this surface by submitting unauthenticated requests that include malformed, missing, or repeated API keys across routes that are intended to be user‑scoped. One concrete pattern is a route like /api/v1/invoices/:id that accepts an X‑API‑Key header and uses a Hanami repository to fetch records. If the authorization policy does not enforce that the key maps to a user who owns the invoice :id, an attacker can iterate over IDs and access invoices belonging to other users. This is a BOLA/IDOR condition that is amplified when API keys are treated as opaque tokens without ownership binding.

Another Beast Attack vector appears when keys are accepted in the URL path (e.g., /api/:api_key/resource) and Hanami’s routing constraints are not restrictive enough. An attacker can probe endpoints with arbitrary path segments and observe differences in response timing or error messages, leading to key enumeration. middleBrick’s input validation and rate‑limiting checks look for inconsistent behavior when keys are placed in paths versus headers, and it flags endpoints that do not enforce strict key formats or reject unexpected characters. The scanner also tests for missing revocation and rotation mechanisms, which can leave compromised keys active for extended periods.

Because Hanami applications often integrate with external services, keys may be forwarded to downstream APIs without additional validation. This can expose the application to SSRF or unsafe consumption patterns when the key is embedded in query strings that reach external hosts. middleBrick’s checks for unsafe consumption and SSRF validate that outbound calls do not inadvertently leak keys or accept attacker‑controlled URLs that could exfiltrate key material. The LLM/AI Security checks are relevant when models are used to generate API documentation or examples; middleBrick scans for accidental key leakage in model outputs and tests for prompt injection that could coax key values from system prompts.

Overall, the combination of weak key binding, permissive routing, and insufficient validation creates a Beast Attack surface where an attacker can escalate from key discovery to unauthorized data access. middleBrick identifies these patterns by correlating authentication checks with BOLA/IDOR and input validation findings, providing prioritized remediation guidance tied to real OWASP API Top 10 categories and related compliance mappings.

Api Keys-Specific Remediation in Hanami — concrete code fixes

Remediation centers on strict validation, binding keys to identities, and avoiding key exposure in logs or URLs. Use Hanami’s built-in authorization and validation infrastructure to enforce that each API key maps to a specific user and that operations are constrained to that user’s resources.

Example: Secure API key authentication with binding and validation

# app/actions/api/v1/base.rb
module Api
  module V1
    class Base < Hanami::Action
      private

      def authenticate_api_key!(headers)
        key = headers['HTTP_X_API_KEY']
        raise Hanami::Action::UnauthorizedError, 'Missing API key' unless key&.match?(/\\'[A-Za-z0-9_-]{32,64}\\')

        @current_user = UserRepository.new.find_by_api_key(key)
        raise Hanami::Action::ForbiddenError, 'Invalid API key' unless @current_user
      end
    end
  end
end
# app/actions/api/v1/invoices/show.rb
module Api
  module V1
    class InvoicesShow < Api::V1::Base
      def call(params)
        authenticate_api_key!(headers)
        invoice = InvoiceRepository.new.find(params[:id])

        if invoice.nil? || invoice.user_id != @current_user.id
          raise Hanami::Action::ForbiddenError, 'Not found'
        end

        self.status = 200
        self.body = { invoice: invoice }

Enforce scope and avoid key in URLs

Do not place API keys in URL paths. Use standard headers only. If you must support query parameters for legacy reasons, treat them as read‑only and map them to a header internally before authorization.

# config/routes.rb
Routable.configure do
  # Good: key in header, not path
  get '/api/v1/invoices/:id', to: 'api/v1/invoices#show', constraints: { method: :get }

  # Avoid: get '/api/:api_key/invoices/:id', to: 'api/v1/invoices#show'
end

Key rotation and revocation

Implement a mechanism to mark keys as revoked and to rotate them periodically. Store a per‑key version or timestamp and reject keys that are on the revoked list.

# app/repositories/user_repository.rb
class UserRepository
  def find_by_api_key(key)
    # Verify key is not revoked
    return nil if RevokedApiKey.exists?(key_hash: Digest::SHA256.hexdigest(key))

    User.where(api_key: key).first
  end
end

Logging and error handling

Ensure API keys are never logged. Sanitize headers in development and production alike.

# config/initializers/hanami_logger.rb
Hanami::.configure do
  logger.filter_parameters += [:api_key, :x_api_key]
end

middleBrick’s CLI can be used to verify these fixes by rescans; for teams with CI/CD, the GitHub Action can enforce that new routes do not introduce key‑in‑path patterns. The MCP Server allows you to trigger scans directly from your IDE while you modify Hanami policies.

Frequently Asked Questions

Can middleBrick detect Beast Attack patterns when API keys are in query strings?
Yes. middleBrick tests endpoints that accept keys in query parameters and checks for weak binding and BOLA/IDOR conditions. It flags routes that do not enforce strict ownership checks.
Does middleBrick provide code fixes for Hanami key handling?
No. middleBrick detects and reports findings with remediation guidance, but it does not modify Hanami code. Use the provided examples as a starting point to implement secure key validation and binding.