HIGH injection flawschiapi keys

Injection Flaws in Chi with Api Keys

Injection Flaws in Chi with Api Keys — how this specific combination creates or exposes the vulnerability

Chi is a lightweight HTTP client for Elixir that supports pluggable authentication, including api_key configurations. When api_keys are handled in Chi, the risk of injection arises primarily from how keys are interpolated into requests and how they are sourced. An injection flaw occurs when untrusted input influences the api_key value or the way it is embedded into headers, query parameters, or the request URL.

Chi allows api_key authentication via two common patterns: header injection and query injection. For header-based authentication, developers often set headers dynamically using values that may originate from user input or external sources. Consider the following example where an api_key from user-controlled parameters is passed directly into a Chi request header without validation or escaping:

api_key = params["api_key"]
request = Tesla.get("https://api.example.com/data", [{"x-api-key", api_key}])

If the api_key contains newline characters, spaces, or crafted header-like sequences, an attacker can inject additional headers or manipulate the request line. For instance, a value like mykey\r\nX-Evil: injected can lead to header injection, potentially bypassing intended routing or authentication logic. This maps to the broader Injection category in the OWASP API Top 10 and can be detected by middleBrick’s Input Validation and Authentication checks, which flag unsafe handling of credentials and missing sanitization.

Query injection with api keys occurs when the key is appended as a URL parameter. Chi supports query parameters via the params option, but if these are built from unescaped user input, an attacker can manipulate the query structure:

api_key = params["key"]
request = Tesla.get("https://api.example.com/search", [params: [api_key: api_key]])

An unsafe api_key such as abc&debug=true would extend the query with an additional parameter, possibly altering behavior or exposing sensitive data in logs. Because query strings often appear in server logs and URLs, leaked api_keys can lead to privilege escalation or unauthorized access, a scenario covered by middleBrick’s Property Authorization and Data Exposure checks. In environments where api_keys are used as bearer tokens, SSRF can also be chained if the injection affects endpoint resolution, a pattern identified by middleBrick’s SSRF and Unsafe Consumption tests.

Another subtle vector involves configuration interpolation in Chi adapters. Developers may define api_key defaults in configuration files or environment variables that are later interpolated into request structures. If these interpolations are not properly constrained, template injection or command injection can occur when system commands are used to fetch keys. For example, using System.get_env("API_KEY") without validation is generally safe, but piping or eval-based retrieval in build scripts can introduce command injection. middleBrick’s LLM/AI Security checks look for indicators of unsafe key derivation, while its BFLA/Privilege Escalation analysis examines whether overly permissive scopes are assigned to keys that should be narrowly scoped.

Because Chi configurations often coexist with other libraries, an api_key injected via a compromised configuration source may propagate across multiple services. middleBrick’s Inventory Management and Encryption checks help identify whether keys are transmitted over insecure channels or stored in plaintext configurations. Real-world attack patterns such as CVE-2021-31054, which involved improper validation of authentication tokens, illustrate the impact of weak injection defenses. By scanning unauthenticated endpoints and analyzing OpenAPI specs with full $ref resolution, middleBrick correlates spec-defined api_key usage with runtime behavior to highlight mismatches and unsafe practices.

Api Keys-Specific Remediation in Chi — concrete code fixes

Remediation focuses on strict validation, safe encoding, and avoiding direct concatenation of user input into api_key usage. Always treat api_key values as opaque strings and never allow them to be controlled beyond a trusted source such as environment variables or secure vaults.

1. Validate and sanitize api_key inputs

Before using an api_key, validate its format and reject unexpected characters. Use a strict allowlist approach for permitted characters (e.g., alphanumeric and limited punctuation):

def valid_api_key?(key) when is_binary(key) do
  Regex.match?(~r/\A[a-zA-Z0-9_\-]{20,64}\z/, key)
end

api_key = params["api_key"]
if valid_api_key?(api_key) do
  Tesla.get("https://api.example.com/data", [{"x-api-key", api_key}])
else
  {:error, :invalid_api_key}
end

This mitigates header and query injection by ensuring the key cannot contain control characters or delimiters used in HTTP.

2. Use Chi’s built-in auth libraries safely

Chi integrates with Tesla and other adapters that support plug_auth. Prefer using dedicated authentication libraries instead of manually setting headers. For api_key authentication, use a custom Tesla middleware that adds the key safely:

defmodule SafeKeyMiddleware do
  def init(opts), do: opts

  def call(env, opts) do
    key = Keyword.fetch!(opts, :api_key)
    Tesla.put_header(env, "x-api-key", key)
  end
end

# In your client definition
client = Tesla.client([SafeKeyMiddleware, {Tesla.Adapter.Hackney, []}], nil)
tesla_client = Tesla.middleware(client, SafeKeyMiddleware, api_key: System.get_env("SAFE_API_KEY"))
Tesla.get(tesla_client, "https://api.example.com/data")

This pattern isolates the key from request-building logic and prevents accidental leakage via user input.

3. Avoid query parameters for sensitive keys

Prefer header-based transmission over query parameters to reduce exposure in logs and URLs. If query usage is unavoidable, ensure keys are passed via encoded params and never concatenated as raw strings:

api_key = System.get_env("API_KEY")
request = Tesla.get("https://api.example.com/search", [params: [key: api_key]])

Never do:

unsafe_key = params["key"] <> System.get_env("DEBUG_SUFFIX")
request = Tesla.get("https://api.example.com/search", [params: [key: unsafe_key]])

Using middleBrick’s Pro plan, you can enable continuous monitoring to detect regressions in how api_keys are handled across Chi-based services. The GitHub Action can fail builds if insecure patterns are detected in scanned codebases, while the MCP Server allows AI coding assistants to flag unsafe usage in real time during development.

Frequently Asked Questions

Can middleBrick detect api_key injection risks in Chi configurations?
Yes. middleBrick scans unauthenticated endpoints and analyzes OpenAPI specs with full $ref resolution to identify unsafe api_key handling patterns, including injection risks mapped to OWASP API Top 10.
Does middleBrick fix api_key injection issues automatically?
No. middleBrick detects and reports findings with remediation guidance. It does not fix, patch, block, or remediate. Use the provided guidance to update your Chi configuration and validation logic.