HIGH ssrf server sidechiapi keys

Ssrf Server Side in Chi with Api Keys

Ssrf Server Side in Chi with Api Keys

Server-side request forgery (SSRF) in a Chi-based API that relies on API keys creates a specific attack pattern where an attacker forces the server to make authenticated requests to internal or third-party endpoints. Chi is a common HTTP router for OCaml, and when handlers use API keys to call downstream services, improper handling of user-supplied URLs can lead to SSRF.

Consider a handler that forwards a request to a backend service using an API key passed in a header. If the target URL is taken directly from user input without strict validation, an attacker can supply internal addresses such as http://169.254.169.254/latest/meta-data/iam/security-credentials/ (AWS metadata service) or internal Kubernetes service endpoints. Because the request includes an API key, the backend call appears authenticated, potentially bypassing network-level restrictions that would otherwise prevent access to internal services.

In Chi, this pattern might look like constructing an HTTP client call with a user-provided URL and adding an Authorization header derived from an API key. If the API key is sourced from configuration and reused across calls, SSRF can escalate to data exposure or privilege abuse depending on the permissions attached to the key. For example, if the key has read access to sensitive resources, an SSRF vulnerability can become a data exfiltration path.

OpenAPI specifications can help detect such risks during scans. middleBrick performs unauthenticated SSRF checks by analyzing spec paths and parameters, then correlating runtime behavior. If a parameter is marked as required but not constrained to a strict schema (e.g., must be a public domain with no internal IPs), SSRF opportunities are flagged. The scanner also tests for missing validation on hostnames and schemes, which are common SSRF vectors in Chi services that dynamically build requests.

Because Chi does not enforce URL restrictions by default, developers must explicitly validate and sanitize inputs. An SSRF finding from middleBrick will include severity, a description of how an attacker could leverage the endpoint, and remediation guidance. This ensures teams understand the risk even when the API key usage itself is correctly implemented.

Api Keys-Specific Remediation in Chi

Remediation focuses on strict URL validation, avoiding dynamic construction of targets from user input, and isolating API key usage to trusted backend calls. When using API keys in Chi handlers, ensure that any outbound request target is limited to a predefined allowlist of hosts and paths.

Example of a vulnerable Chi handler that accepts a URL parameter and forwards it with an API key:

let handler (apiKey: string) (req : Request) : Response =
  let targetUrl = QueryParam.get "url" req.query
  let client = new HttpClient()
  client
    .GetStringAsync($"{targetUrl}")
    .Result
    .ToString()

This code takes url directly from the query string and uses it in a request, attaching an API key on the server side (not shown). An attacker can supply http://127.0.0.1 or internal metadata endpoints, leading to SSRF.

Secure version with validation and a fixed target:

let allowedHosts = Set ["api.example.com"; "internal.service.svc"]

let isValidTarget (url: Uri) : bool =
  Uri.CheckHostName(url.Host) = UriHostNameType.Dns &&
  Set.contains url.Host allowedHosts &&
  url.Scheme = Uri.UriSchemeHttps

let handler (apiKey: string) (req : Request) : Response =
  match QueryParam.getOpt "target" req.query with
  | None -> Response.badRequest "missing target"
  | Some rawUrl -
    match Uri.TryCreate(rawUrl, UriKind.Absolute, ref Uri()) with
    | false, _ -> Response.badRequest "invalid URL"
    | true, uri -
      if not (isValidTarget uri) then
        Response.forbidden "target not allowed"
      else
        use client = new HttpClient()
        client.DefaultRequestHeaders.Authorization <- AuthenticationHeaderValue("Bearer", apiKey)
        let! content = client.GetStringAsync(uri) |> Async.AwaitTask
        Response.ok content

Key remediation steps:

  • Do not concatenate user input into URLs; use a fixed base URL where possible.
  • Validate the host against an allowlist and enforce HTTPS.
  • Keep API keys in server-side configuration and avoid exposing them to client-controlled parameters.
  • If multiple downstream services are needed, maintain a mapping of allowed endpoints rather than accepting free-form URLs.

middleBrick’s Pro plan supports continuous monitoring for such misconfigurations. You can integrate the GitHub Action to fail builds if a Chi API route is flagged for SSRF or if the security score drops below your defined threshold.

Frequently Asked Questions

Can SSRF in Chi be exploited even when API keys are rotated regularly?
Yes. SSRRF is about unauthorized internal requests; rotating keys limits lateral movement but does not prevent an attacker from forcing the server to make unwanted authenticated calls. Input validation and host allowlisting remain essential.
Does middleBrick test for SSRF when scanning a Chi API secured with API keys?
middleBrick scans the unauthenticated attack surface and can detect SSRF vectors even when API keys are used server-side. The scanner analyzes spec definitions and runtime behavior to identify missing URL constraints and unsafe parameter usage.