HIGH api key exposurephoenixbearer tokens

Api Key Exposure in Phoenix with Bearer Tokens

Api Key Exposure in Phoenix with Bearer Tokens — how this specific combination creates or exposes the vulnerability

In Phoenix applications that rely on HTTP bearer tokens for API authentication, exposure typically arises when tokens are handled with inconsistent security practices across the request lifecycle. A bearer token is a simple credential sent in the Authorization header as Authorization: Bearer <token>. When this pattern is used in Phoenix endpoints that accept user-supplied input, misconfigurations can inadvertently expose the token or allow it to be reflected into logs, error pages, or downstream services.

One common exposure vector is logging full request metadata, including headers. If a Phoenix logger is configured to log request headers indiscriminately, the Authorization header containing the bearer token can appear in log files or monitoring dashboards, creating a data exposure finding. Another vector occurs when error messages include the Authorization header value, for example during malformed request handling or when upstream services return detailed responses that bubble up the header to the client. These patterns are surfaced by security scans that test data exposure and input validation, and they map to findings such as OWASP API Top 10:2023 A05 (Security Misconfiguration) and A07 (Identification and Authentication Failures).

SSRF and open redirect patterns can also interact with bearer token usage. If your Phoenix app accepts a URL from user input and makes an HTTP request using the same bearer token, an attacker can supply an internal endpoint to exfiltrate the token through a SSRF-induced request to a metadata or internal service. Similarly, if the Authorization header is forwarded to third‑party services without scrubbing, you risk token leakage beyond the intended trust boundary. Scans that include SSRF and Unsafe Consumption checks can identify whether your endpoints forward or consume external inputs in a way that risks exposing bearer tokens.

Operational exposure can occur when OpenAPI specs are published with examples containing real bearer tokens, or when developers embed tokens in seed scripts or configuration files that are committed to version control. Because middleBrick scans OpenAPI/Swagger specs (2.0, 3.0, 3.1) with full $ref resolution and cross-references spec definitions with runtime behavior, it can detect mismatches such as example tokens in documentation that do not appear as required security schemes, highlighting gaps in Inventory Management and Data Exposure controls.

To illustrate, consider a simple Phoenix controller that proxies a request and echoes an Authorization header in debug output. If the debug route is reachable in production, it can act as an information leak channel. A security scan that includes Input Validation and Data Exposure checks would flag this as a finding, providing remediation guidance to remove or protect sensitive header reflection and enforce strict allowlists on inputs.

Compliance mappings are relevant here: findings related to bearer token exposure typically align with PCI-DSS, SOC2, and GDPR expectations around protecting authentication credentials. The scanner reports these as prioritized findings with severity and remediation steps, enabling teams to address the specific control weaknesses without relying on speculative internal architecture details.

Bearer Tokens-Specific Remediation in Phoenix — concrete code fixes

Remediation focuses on ensuring bearer tokens are never logged, echoed to clients, or stored in examples, and that they are handled consistently across requests and dependencies. Below are concrete patterns and code snippets for a secure Phoenix approach.

1. Avoid logging or echoing bearer tokens

Configure your logger to exclude the Authorization header. In config/config.exs, adjust the Plug logger metadata filter to skip sensitive headers:

# config/config.exs
config :logger, :console,
  metadata_filter: ["authorization", "cookie"]

In your controller, avoid inspecting or logging req.headers["authorization"]. If you must include request context for debugging, redact the token:

# lib/my_app_web/controllers/debug_controller.ex
defmodule MyAppWeb.DebugController do
  use MyAppWeb, :controller

  def show(conn, _params) do
    auth_header = get_req_header(conn, "authorization")
    redacted = if auth_header != [], do: "[Bearer redacted]", else: "none"
    json(conn, %{debug: %{authorization: redacted}})
  end
end

2. Validate and scope incoming Authorization headers

Ensure that only expected formats are accepted and that tokens are not forwarded to untrusted endpoints. Add a pipeline or plug that validates the Authorization header early:

# lib/my_app_web/plugs/auth_header_validator.ex
defmodule MyAppWeb.AuthHeaderValidator do
  import Plug.Conn

  def init(opts), do: opts

  def call(conn, _opts) do
    case get_req_header(conn, "authorization") do
      ["Bearer " <> token] when byte_size(token) > 10 and byte_size(token) < 512 ->
        # attach a sanitized value if needed, or continue
        conn
      _ ->
        conn
        |> put_status(:bad_request)
        |> json(%{error: "Invalid Authorization header"})
        |> halt()
    end
  end
end

Plug this into your router or pipeline to reject malformed or suspicious bearer tokens before they reach sensitive actions.

3. Prevent SSRF and unsafe consumption when using bearer tokens

If your Phoenix app makes outbound HTTP requests using a bearer token, avoid forwarding user-supplied URLs directly. Use a strict allowlist of hosts and ensure the token is not attached to requests to untrusted origins:

# lib/my_app_web/controllers/proxy_controller.ex
defmodule MyAppWeb.ProxyController do
  use MyAppWeb, :controller
  @allowed_hosts ["api.example.com", "internal.service.local"]

  def proxy(conn, %{"url" => url}) do
    uri = URI.parse(url)
    if Enum.member?(@allowed_hosts, uri.host) do
      token = List.first(get_req_header(conn, "authorization")) || ""
      headers = [{"authorization", token}]
      # Perform request with strict host and timeout controls
      case HTTPoison.get(url, headers, timeout: 5000) do
        {:ok, resp} -> json(conn, %{status: resp.status_code})
        {:error, _} -> json(conn, %{error: "upstream error"})
      end
    else
      json(conn, %{error: "host not allowed"})
    end
  end
end

This pattern reduces SSRF risk and prevents accidental token exposure to external services.

4. Secure OpenAPI specs and CI/CD practices

Ensure your OpenAPI spec does not contain example bearer tokens. Use securitySchemes to describe the scheme without examples:

# openapi.yaml
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - bearerAuth: []

Use the middleBrick CLI to scan your endpoint and spec: middlebrick scan <url>. The scan will highlight any spec/runtime mismatches and provide remediation guidance tied to findings such as Data Exposure and Inventory Management.

5. Enforce continuous monitoring

For ongoing protection, adopt the Pro plan to enable continuous monitoring and CI/CD integration. Configure the GitHub Action to fail builds if risk scores exceed your threshold, ensuring future changes do not reintroduce bearer token exposure.

Frequently Asked Questions

Can a logged Authorization header in Phoenix logs lead to API key exposure?
Yes. If the Authorization header containing a bearer token is logged in full, it can be exposed in log stores or monitoring dashboards, leading to data exposure and authentication compromise. Filter or redact the header at the logger level.
Does middleBrick detect bearer token exposure in OpenAPI specs and runtime behavior?
Yes. middleBrick scans OpenAPI/Swagger specs (2.0, 3.0, 3.1) with full $ref resolution and cross-references spec definitions with runtime findings. It can flag mismatches such as example tokens in documentation and highlights Data Exposure and Inventory Management findings with remediation guidance.