Container Escape in Hanami with Bearer Tokens
Container Escape in Hanami with Bearer Tokens — how this specific combination creates or exposes the vulnerability
A container escape in Hanami combined with bearer token handling can occur when token validation is incomplete and the runtime environment is not properly isolated. Hanami is a Ruby web framework, and like any framework that relies on bearer tokens for authentication, its security depends on how tokens are validated, stored, and scoped within containerized deployments.
In a containerized setup, a compromised Hanami process might attempt to break out of its container namespace. If bearer tokens are accepted without strict validation of scope, audience, and issuer, an attacker can supply a token that impersonates a higher-privileged service account. When Hanami trusts the token’s contents without verifying signatures rigorously, it may propagate identity claims into downstream services or host system calls, effectively widening the attacker’s reach.
For example, if Hanami uses a middleware that parses the Authorization header as Bearer <token> and then directly maps claims to filesystem paths or container environment variables, an attacker can craft a token with a misleading sub or role claim to access unintended resources. This can lead to host-level file reads or executions when the container’s security context is misconfigured, such as when the process runs with elevated capabilities or mounts sensitive host directories.
Consider an unsafe Hanami route that decodes a bearer token without verifying the signature algorithm, assuming the token is trustworthy because it was issued by an internal auth service. If the container shares the host’s PID namespace or has access to the Docker socket, an attacker who obtains a valid token can exploit this trust to execute commands on the host through the Hanami process. The interaction between token-based identity and container isolation weaknesses is the crux of this attack surface.
During a middleBrick scan, this scenario is tested under the BOLA/IDOR and Property Authorization checks, as well as Input Validation and Unsafe Consumption. The scanner submits requests with manipulated bearer tokens to observe whether Hanami enforces strict token validation, respects scopes, and prevents privilege escalation through identity confusion. Findings include missing audience checks, lack of token binding, and overly permissive container policies that allow a compromised Hanami app to interact with the host filesystem or other containers.
Bearer Tokens-Specific Remediation in Hanami — concrete code fixes
Remediation focuses on strict token validation, scope enforcement, and defense in depth within Hanami. Always verify the token signature, issuer, audience, and expiration using a trusted library. Avoid manually parsing the Authorization header without cryptographic checks.
Example of unsafe token handling in Hanami before fix:
# Unsafe: assumes token is valid
class Auth::CurrentUser
def initialize(request)
@request = request
end
def call
token = @request.headers['Authorization']&.split(' ')&.last
# Dangerous: no signature or claim verification
payload = JWT.decode(token, nil, false).first
@user = User.find_by(sub: payload['sub'])
end
end
Example of safe token handling in Hanami after fix:
# Safe: validates signature, issuer, audience, and exp
require 'jwt'
class Auth::CurrentUser
ALGORITHM = 'RS256'
AUDIENCE = 'https://api.myapp.com'
ISSUER = 'https://auth.myapp.com'
def initialize(request, key_provider)
@request = request
@key_provider = key_provider
end
def call
token = extract_token
decoded = JWT.decode(
token,
->(header) { @key_provider.fetch(header['kid']) },
true,
{ algorithm: ALGORITHM, iss: ISSUER, aud: AUDIENCE }
)
payload = decoded.first
validate_claims(payload)
@user = User.find_by(sub: payload['sub'])
rescue JWT::ExpiredSignature, JWT::VerificationError, JWT::DecodeError
raise UnauthorizedError, 'Invalid token'
end
private
def extract_token
header = @request.headers['Authorization']
return nil unless header&.start_with?('Bearer ')
header.split(' ').last
end
def validate_claims(payload)
raise UnauthorizedError, 'Token scope insufficient' unless payload['scope']&.include?('api:read')
# additional custom claim checks
end
end
Additional remediation steps:
- Enforce token binding by correlating the token jti (JWT ID) with a session or one-time use record to prevent replay.
- Apply least-privilege roles and scopes to bearer tokens and validate them on each request in Hanami policies.
- Run Hanami in containers with minimal privileges, drop unnecessary capabilities, and avoid mounting the Docker socket.
- Use short-lived tokens and refresh token rotation to reduce the window for token theft abuse.
- Leverage middleBrick’s CLI to scan your Hanami endpoints:
middlebrick scan https://api.example.com. With the Pro plan, enable continuous monitoring and GitHub Action integration to fail CI/CD pipelines if risky token handling or authorization bypass patterns are detected.