Brute Force Attack in Hanami with Bearer Tokens
Brute Force Attack in Hanami with Bearer Tokens — how this specific combination creates or exposes the vulnerability
A brute force attack against a Hanami application that relies on Bearer tokens attempts to discover valid tokens by systematically guessing or iterating through possible values. In this context, the vulnerability arises when token validation does not adequately limit the rate of authentication attempts or when token formats are predictable. Hanami routes API requests to controllers where token presence is typically checked before authorization decisions are made. If an endpoint accepts a Authorization: Bearer <token> header without enforcing strong anti-automation controls, an attacker can mount credential stuffing or token enumeration attacks against the API surface.
Consider an API route like POST /api/v1/accounts/:account_id/transactions that expects a Bearer token in the request header. Without proper rate limiting or token introspection safeguards, an attacker can automate requests with guessed tokens and observe differences in response behavior—such as 200 OK versus 403 Forbidden—to infer validity. Because Bearer tokens are often high-entropy strings, the risk is not trivial guessing but rather token discovery via insufficiently protected endpoints or weak token entropy. The attack surface is the unauthenticated path that still accepts Bearer tokens, enabling black-box probing of authorization boundaries.
In a real-world scenario, an attacker might use a list of leaked tokens or generate candidates based on weak entropy sources, sending requests with headers such as Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. If the application returns detailed error messages or inconsistent HTTP status codes, it may leak information about token validity. Moreover, if token revocation or rotation is not enforced, compromised tokens remain usable until expiration. This combination of predictable token handling, permissive unauthenticated access, and informative responses can facilitate account takeover or unauthorized data access within Hanami services.
Bearer Tokens-Specific Remediation in Hanami — concrete code fixes
Remediation focuses on ensuring Bearer token validation is strict, rate-limited, and resistant to enumeration. In Hanami, you can enforce token checks within action-level before filters and ensure responses do not reveal token validity. The following Hanami controller example demonstrates a robust pattern for Bearer token verification with constant-time comparison and clear separation of concerns.
require "hanami/controller"
module Web::Controllers::Api::V1
class BaseAction
include Hanami::Action
private
def authenticate_bearer_token!
auth_header = request.env["HTTP_AUTHORIZATION"]
return halt_unauthorized unless auth_header&.start_with?("Bearer ")
token = auth_header.split(" ", 2).last
# Use constant-time comparison to avoid timing attacks
valid = secure_compare(token, expected_token)
halt_unauthorized unless valid
end
def expected_token
# Retrieve token securely from environment or encrypted configuration
ENV["API_BEARER_TOKEN"]
end
def secure_compare(a, b)
return false if a.nil? || b.nil? || a.bytesize != b.bytesize
l = a.unpack "C*"
res = 0
b.each_byte { |byte| res |= byte ^ l.shift }
res == 0
end
def halt_unauthorized
self.status = 401
self.body = { error: "Unauthorized" }.to_json
halt
end
end
end
In this example, the authenticate_bearer_token! method checks for the Bearer prefix, extracts the token, and performs a constant-time comparison using secure_compare to mitigate timing attacks. The token is sourced from an environment variable, avoiding hardcoded secrets. Apply this filter to relevant actions or use a base controller to enforce authentication across API endpoints.
Additionally, integrate rate limiting at the rack layer or within your deployment infrastructure to restrict the number of requests with Bearer tokens from a single IP or token within a time window. For example, using rack-attack in a Hanami application can limit brute force attempts:
# config/initializers/rack_attack.rb
class Rack::Attack
throttle("bearer_token_attempts/ip", limit: 30, period: 60) do |req|
if req.path.start_with?("/api") && req.get? == false
req.env["HTTP_AUTHORIZATION"]&.split(" ")&.last
end
end
throttle("bearer_token_attempts/token", limit: 100, period: 60) do |req|
if req.path.start_with?("/api") && req.get? == false
auth = req.env["HTTP_AUTHORIZATION"]
auth.split(" ")&.last if auth&.start_with?("Bearer ")
end
end
self.throttled_response = lambda do |env|
[
429,
{ "Content-Type" => "application/json" },
[{ error: "Too many requests" }].to_json
]
end
end
These measures ensure that brute force attempts against Bearer token endpoints are constrained, and token validation remains resistant to leakage. Combine this with secure token generation, short expiration times, and regular rotation to reduce the impact of any potential compromise.