HIGH identification failureshanamibearer tokens

Identification Failures in Hanami with Bearer Tokens

Identification Failures in Hanami with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Identification failures occur when an API fails to correctly assert and enforce the identity of a caller. In Hanami applications that rely on Bearer Tokens, this can manifest in multiple dimensions: authentication, authorization, and token handling. Because Hanami is a Ruby web framework that encourages explicit, object-oriented design, the way tokens are parsed, validated, and scoped can introduce subtle gaps if not implemented consistently.

First, authentication gaps arise when Bearer Tokens are accepted but not rigorously verified against a trusted identity store. For example, a Hanami endpoint might inspect the Authorization header for a Bearer pattern but skip confirming token validity, expiry, or revocation. An attacker can therefore supply any string in the format Bearer <token> and gain access if the backend does not validate the token signature or provenance. This is an authentication bypass vector that maps to the BOLA/IDOR and Authentication checks in middleBrick’s 12 parallel security scans.

Second, authorization failures (a subset of Identification Failures) occur when a Hanami app confirms a token is valid but does not ensure the associated subject is permitted to access the requested resource. Imagine a Hanami app that identifies a user from a Bearer Token but then uses a simple ID from the token to fetch records without scoping queries. An attacker can iterate through numeric IDs or UUIDs and access data belonging to other users. This specific flaw is covered by middleBrick’s BOLA/IDOR and Property Authorization checks, which correlate spec definitions with runtime behavior to uncover insecure direct object references.

Third, token handling weaknesses emerge when Bearer Tokens are logged, echoed, or cached inadvertently. In Hanami, if request logging middleware prints the full header or if debug output includes the token, sensitive credentials may leak. Similarly, if tokens are stored in query parameters or poorly isolated server-side sessions, they can be exposed through logs or browser history. middleBrick’s Data Exposure and Unsafe Consumption checks are designed to surface these risks by analyzing the OpenAPI spec and runtime responses for indicators such as tokens in URLs or unencrypted transport.

To illustrate, consider a Hanami controller that naïvely trusts a Bearer Token without verifying its signature:

module Web::Controllers::Accounts
  class Show
    include Web::Action

    def call(params)
      token = request.env["HTTP_AUTHORIZATION"]&.split(" ")&.last
      # Risk: No validation of token authenticity or scope
      account = AccountRepository.new.find(params[:id])
      self.body = { account: account }.to_json
    end
  end
end

In this snippet, the token is extracted but never validated; the endpoint then loads an account by an ID provided in the URL. An attacker can change the :id to access other accounts, demonstrating a combined identification and authorization failure. middleBrick would flag this as a high-severity BOLA/IDOR finding with remediation guidance to validate the token and scope data access to the subject encoded in the token.

Finally, unauthenticated LLM endpoint detection is a unique check in middleBrick that can identify endpoints leaking system prompts or behaving like an LLM service when Bearer Tokens are absent or malformed. While not directly about Hanami, this illustrates how identification failures can be probed automatically across the unauthenticated attack surface.

Bearer Tokens-Specific Remediation in Hanami — concrete code fixes

Remediation focuses on strict token validation, scoping, and safe handling within Hanami’s architecture. Always verify the token before establishing identity, enforce least-privilege scope, and avoid leaking credentials in logs or responses.

1. Validate Bearer Tokens before identifying a subject

Ensure every request containing a Bearer Token is authenticated against a trusted provider (e.g., an OAuth introspection endpoint or a signed JWT verification routine). Do not treat the presence of a token as proof of identity.

module Web::Controllers::Base
  class Action
    include Web::Action

    protected

    def current_user(token)
      return nil unless token&.start_with?("Bearer ")
      token_value = token.split(" ").last
      # Verify token signature, expiry, and revocation here
      # Example with a hypothetical JWT verifier:
      return nil unless JWTVerifier.valid?(token_value)
      subject_id = JWTVerifier.payload(token_value)["sub"]
      UserRepository.new.find(subject_id)
    rescue JWTVerifier::InvalidTokenError
      nil
    end
  end
end

2. Scope data access to the authenticated subject

After identifying the subject from a valid token, scope all queries so users can only access their own data. Never rely solely on URL parameters for authorization.

module Web::Controllers::Accounts
  class Show
    include Web::Action

    def call(params)
      auth_header = request.env["HTTP_AUTHORIZATION"]
      user = current_user(auth_header)
      if user.nil?
        self.status = 401
        self.body = { error: "unauthorized" }.to_json
        return
      end

      # Enforce ownership: scope by user identity, not user-supplied ID
      account = AccountRepository.new.where(user_id: user.id).find(params[:id])
      if account.nil?
        self.status = 404
        self.body = { error: "not_found" }.to_json
        return
      end
      self.body = { account: account }.to_json
    end
  end
end

3. Avoid logging or exposing Bearer Tokens

Configure request logging to redact authorization headers and ensure tokens are never stored in query strings or client-side storage where they can be leaked.

# config/initializers/logging.rb
class RedactingLogger
  def call(io)
    ->(env) do
      env["HTTP_AUTHORIZATION"] = "[FILTERED]" if env["HTTP_AUTHORIZATION"]
      @app.call(io).tap { |_, headers, body| /* safe logging */ }
    end
  end
end

4. Enforce HTTPS and short token lifetimes

Serve all endpoints over HTTPS to prevent token interception, and prefer short-lived tokens with refresh mechanisms. In Hanami, you can integrate middleware to reject tokens issued over insecure channels.

5. Use middleBrick to validate your implementation

Run middleBrick scans to verify that authentication, BOLA/IDOR, Data Exposure, and Unsafe Consumption checks pass. The CLI provides quick feedback:

$ middlebrick scan https://api.example.com

For CI/CD, use the GitHub Action to fail builds when risk scores drop below your chosen threshold, and leverage the Web Dashboard or MCP Server in your AI coding assistant to track improvements over time.

Frequently Asked Questions

How does middleBrick detect Bearer Token handling issues in Hanami APIs?
middleBrick runs unauthenticated scans that inspect the OpenAPI/Swagger spec and runtime behavior for authentication gaps, BOLA/IDOR patterns, and data exposure indicators such as tokens in logs or URLs. It correlates spec definitions with findings to highlight identification failures and provides remediation guidance.
Can middleBrick fix token handling problems automatically?
No. middleBrick detects and reports issues, including identification failures and token exposure risks, along with prioritized findings and remediation guidance. It does not automatically fix, patch, or block endpoints.