Broken Authentication in Hanami with Api Keys
Broken Authentication in Hanami with Api Keys
Broken authentication in Hanami when using API keys typically arises from weak handling of static credentials, predictable key generation, and insufficient validation at the application boundary. Hanami applications that rely solely on API keys for authentication must ensure keys are long, random, and scoped to specific operations or services. If keys are stored in plaintext, passed over unencrypted channels, or logged inadvertently, the authentication boundary collapses.
An attacker may exploit endpoints that accept API keys via query parameters or non-secure headers, especially if the framework’s route constraints are not strict. For example, a route defined as get "/admin/:id", AdminController, :show without additional constraints could allow key guessing or enumeration if responses do not consistently differentiate between missing keys and invalid keys. MiddleBrick’s authentication checks flag inconsistent error handling and missing key binding to a verified identity as risk indicators.
Additionally, if Hanami middleware does not enforce HTTPS for all routes, API keys can be intercepted in transit. The framework’s default configuration may allow HTTP in development, which can accidentally carry over into staging or production. Without transport-layer enforcement, static keys become replayable credentials. MiddleBrick tests for encryption and insecure transmission paths, highlighting whether API keys are ever exposed in cleartext.
Another vulnerability pattern involves key scope and privilege escalation. A key intended for read-only analytics might be accepted by write endpoints due to coarse-grained authorization checks. This mismatch enables attackers to perform actions beyond the key’s intended permissions. MiddleBrick’s BOLA/IDOR and privilege escalation checks look for such authorization gaps by probing endpoints with keys that have differing privilege levels.
Operational practices also contribute to broken authentication. If API keys are rotated infrequently, hardcoded into configuration files, or shared across services without isolation, the attack surface grows. MiddleBrick’s inventory management checks help identify where keys are referenced across endpoints and whether unnecessary exposure exists in OpenAPI specs or debug output.
Api Keys-Specific Remediation in Hanami
Remediation centers on secure key lifecycle management, strict validation, and transport protection. Use cryptographically secure random generators to create keys and store them outside the codebase, such as in environment variables or a secrets manager. Validate the presence and format of keys before routing, and ensure constant-time comparison to prevent timing attacks.
In Hanami, you can enforce API key validation via a custom action that runs before targeted operations. Below is a secure example of an authentication action that validates an API key header and aborts the request if invalid.
# frozen_string_literal: true
# app/actions/api/base.rb
module Api
class Base < Hanami::Action
AUTH_HEADER = 'X-API-Key'.freeze
VALID_KEYS = ENV.fetch('API_KEYS', '').split(',').map(&:strip).freeze
def call(params)
provided = request.env['HTTP_X_API_KEY']
halt 401, { error: 'Unauthorized' }.to_json unless valid_key?(provided)
# proceed to operation-specific action
end
private
def valid_key?(key)
return false if key.nil? || key.empty?
VALID_KEYS.contain?(key)
end
end
end
For route-specific protection, create a dedicated authentication action and include it in your route definitions. This ensures each endpoint explicitly requires a valid key and avoids accidental exposure.
# frozen_string_literal: true
# config/routes.rb
require 'hanami/routing'
Hanami.routes do
namespace :api do
namespace :v1 do
# Apply authentication to a scope
auth = Api::Base
get '/reports', Reports::Index, to: auth
post '/transactions', Transactions::Create, to: auth
end
end
end
Rotate keys regularly and use scoped keys to limit impact. For example, generate separate keys for read and write operations, and store them as distinct environment variables. When validating, ensure you compare keys using a constant-time method to prevent timing-based side channels.
# frozen_string_literal: true
# app/actions/api/secure.rb
module Api
class Secure < Hanami::Action
def call(params)
key = request.env['HTTP_X_API_KEY']
halt 403, { error: 'Forbidden' }.to_json unless secure_key?(key)
# proceed
end
private
def secure_key?(key)
return false if key.nil? || key.strip.empty?
# Use secure comparison
ActiveSupport::SecurityUtils.secure_compare(
key.strip,
ENV.fetch('PRIVILEGED_API_KEY', '')
)
end
end
end
Ensure HTTPS is enforced in production by configuring your web server or reverse proxy to redirect HTTP to HTTPS. Hanami’s configuration should not permit HTTP in environments handling sensitive authentication material. MiddleBrick’s encryption checks verify that API keys are never transmitted in cleartext.
Finally, audit where keys appear in logs and error messages. Avoid logging raw keys by filtering sensitive parameters in Hanami’s request logging pipeline. Combine these measures with MiddleBrick’s continuous monitoring and CI/CD integration to detect regressions early, especially when using the Pro plan for automated scanning on configurable schedules.
Related CWEs: authentication
| CWE ID | Name | Severity |
|---|---|---|
| CWE-287 | Improper Authentication | CRITICAL |
| CWE-306 | Missing Authentication for Critical Function | CRITICAL |
| CWE-307 | Brute Force | HIGH |
| CWE-308 | Single-Factor Authentication | MEDIUM |
| CWE-309 | Use of Password System for Primary Authentication | MEDIUM |
| CWE-347 | Improper Verification of Cryptographic Signature | HIGH |
| CWE-384 | Session Fixation | HIGH |
| CWE-521 | Weak Password Requirements | MEDIUM |
| CWE-613 | Insufficient Session Expiration | MEDIUM |
| CWE-640 | Weak Password Recovery | HIGH |