Auth Bypass in Chi with Api Keys
Auth Bypass in Chi with Api Keys — how this specific combination creates or exposes the vulnerability
Chi is a lightweight HTTP client for Elixir that allows developers to make HTTP requests with minimal boilerplate. When using API keys for authentication in Chi, a common misconfiguration can lead to an authentication bypass scenario. An Auth Bypass vulnerability occurs when access controls are not properly enforced, allowing an unauthenticated or low-privilege actor to reach a protected endpoint. With API keys, this often happens when the key is accepted but not validated for scope, intended recipient, or request context.
In Chi, API keys are typically injected via headers, query parameters, or custom options. If the application routes all requests through a Chi pipeline that attaches the API key to the request but does not verify that the key is intended for the target service or that the key has permissions for the specific operation, an attacker may be able to call a sensitive endpoint by simply providing any valid key. For example, an endpoint that should be limited to administrative actions might be invoked because the key is accepted without checking the requested action or the identity associated with the key.
Consider a Chi client built to call a payment service with an API key passed as a header. If the server endpoint does not validate that the key is tied to the merchant making the request, an attacker who knows or guesses a valid key could initiate transactions on behalf of other merchants. This becomes more likely when keys are long-lived, overly permissive, or shared across services without proper segmentation. The risk is compounded when combined with other weaknesses such as insufficient input validation or missing rate limiting, which can allow automated probing for valid keys.
middleBrick scans such configurations as part of its Authentication and BOLA/IDOR checks, identifying whether API key usage is too permissive or improperly enforced. The tool also tests for BFLA/Privilege Escalation by attempting to access higher-privilege endpoints using lower-privilege keys. Because Chi pipelines often compose multiple request steps, a missing authorization check at one stage can unintentionally grant access to downstream resources. The scanner further examines Data Exposure and Encryption checks to determine whether API keys are transmitted or logged insecurely, which can aid an attacker in key discovery.
Real-world attack patterns mirror these risks. For instance, an unauthenticated LLM endpoint that accepts an API key in a header might return model outputs that should be restricted to authenticated users. middleBrick’s LLM/AI Security module includes Unauthenticated LLM Endpoint detection to flag such exposures. Additionally, the tool checks for System Prompt Leakage and Active Prompt Injection to ensure that API integrations do not inadvertently expose sensitive logic or data through misrouted authenticated calls.
Because middleBrick performs black-box scanning without credentials, it can detect whether an API key alone is insufficient to enforce proper authorization. The scanner runs parallel checks that include Property Authorization and Input Validation to confirm that parameters and payloads are validated even when a key is present. Remediation guidance provided by the report emphasizes tightening key validation, applying least privilege, and correlating keys with specific identities or scopes to reduce the attack surface.
Api Keys-Specific Remediation in Chi — concrete code fixes
To remediate authentication bypass risks when using API keys in Chi, ensure that each key is validated not only for presence but also for correctness, scope, and intended usage. Keys should be bound to specific identities or services and checked against authorization logic before any sensitive action is performed. Below are concrete Chi code examples demonstrating secure handling of API keys.
Example 1: Validating API key ownership before processing a request
defmodule MyApp.PaymentClient do
use Tesla, adapter: Tesla.Adapter.Chi
def build_authorized_merchant_key(merchant_id, raw_key) do
# Derive a key that is tied to the merchant
:crypto.hash(:sha256, "merchant_#{merchant_id}_#{raw_key}")
|> Base.encode16()
end
def call_payment_endpoint(merchant_id, raw_key, amount) do
expected_key = build_authorized_merchant_key(merchant_id, raw_key)
# Chi request includes strict header validation on the server side
# Client ensures the key is correctly scoped to the merchant
Tesla.post(url(), %{"amount" => amount}, [
{"X-API-Key", expected_key},
{"Content-Type", "application/json"}
])
end
end
Example 2: Rejecting requests with non-matching or missing keys in a Chi middleware
defmodule MyApp.KeyValidationMiddleware do
import Tesla.Middleware
def key_validation_middleware(opts) do
{Tesla.Middleware, opts}
end
def call(env, next) do
case env.request_headers |> Enum.find(&match?({"x-api-key", _}, &1)) do
{"x-api-key", key} ->
if MyApp.KeyStore.valid_key_for_scope?(key, env.method, env.url) do
proceed(env, next)
else
{:error, :unauthorized, env}
end
nil ->
{:error, :bad_request, "Missing X-API-Key header"}
end
end
end
Example 3: Using Chi with per-request key rotation and scope checks
defmodule MyApp.SecureClient do
use Tesla, adapter: Tesla.Adapter.Chi
def fetch_with_scope(url, key, allowed_scopes) do
Tesla.get(url, [
{"Authorization", "Bearer #{key}"},
{"X-Scope", Enum.join(allowed_scopes, ",")}
])
|> validate_scope_response(allowed_scopes)
end
defp validate_scope_response({:ok, %{status: 200, body: body}}, allowed_scopes) do\n if body["scope"] in allowed_scopes do
{:ok, body}
else
{:error, :scope_mismatch}
end
end
defp validate_scope_response(error, _), do: error
end
These examples emphasize binding keys to context (merchant ID, scope, method) and validating on both client and server. On the server side, ensure that API key validation includes checks against tenant or user context and that keys are not accepted for actions outside their intended permissions. middleBrick’s Pro plan supports continuous monitoring and GitHub Action integration to detect regressions in key handling as code evolves, helping you fail builds if insecure patterns are introduced.
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 |