HIGH api key exposurechisession cookies

Api Key Exposure in Chi with Session Cookies

Api Key Exposure in Chi with Session Cookies — how this specific combination creates or exposes the vulnerability

Chi is a functional web framework for Clojure that encourages immutability and explicit data flow. When API keys are managed in Chi applications, the framework’s typical patterns can inadvertently expose those keys when session cookies are used for authentication. This occurs when sensitive configuration values, such as third-party API credentials, are stored in server-side session data that is tied to a session cookie. If the session store is not properly isolated or if cookies are transmitted over insecure channels, an attacker who can intercept or predict a session identifier may gain access to the associated API keys through session fixation or session hijacking.

In Chi, session state is often represented as a map that is serialized into a cookie or stored server-side with a cookie reference. If developers embed API keys directly into this session map—such as [::session :api-key "sk_live_xxx"]—the key becomes reachable through any route that reads the session. This becomes a risk when the same session cookie is used across multiple services or micro frontends, increasing the likelihood of cross-service exposure. Additionally, if the application logs session data or error messages without redaction, API keys may be written to logs, creating a secondary exposure path.

The interaction between Chi’s session handling and API key storage is particularly sensitive when the application relies on unauthenticated endpoints that still read session cookies. Even without user authentication, an endpoint that returns session-derived data can leak API keys if those keys are present in the session map. For example, a health-check route that returns session metadata for debugging might inadvertently include the key in an HTTP response if protections like output filtering are not applied. This aligns with the broader category of Data Exposure within middleBrick’s 12 security checks, where scanners detect whether sensitive data such as API keys can be observed without authentication.

Moreover, Chi applications that use persistent or shared session backends—such as Redis or database-backed stores—must ensure that access controls on those stores are strict. A misconfigured Redis instance with no password binding can allow an attacker to retrieve session cookies and, consequently, the API keys stored within them. middleBrick’s detection of unauthenticated endpoints combined with session cookie analysis can surface these issues by identifying routes that expose session-like data without requiring proof of authentication.

Another contributing factor is insecure cookie attributes. If the :secure flag is not set, cookies may be transmitted over HTTP, making them vulnerable to network sniffing. Similarly, missing :http-only flags can expose cookies to client-side scripts, enabling cross-site scripting (XSS) attacks that steal session identifiers and give access to the session-stored API keys. Chi developers must explicitly configure these attributes to reduce the attack surface presented by this combination of framework session handling and key management.

middleBrick’s scans help identify these risks by checking for Data Exposure and Authentication misconfigurations across the unauthenticated attack surface. By correlating findings from the Inventory Management and Unsafe Consumption checks, the scanner can highlight endpoints that reference session data and flag potential key exposure. This enables teams to address the issue before an attacker can exploit the pathway between Chi’s session mechanisms and sensitive credentials.

Session Cookies-Specific Remediation in Chi — concrete code fixes

Remediation focuses on ensuring that API keys never enter the session map and that session cookies are protected with strict attributes and secure storage practices. Developers should use Chi’s built-in session configuration to enforce secure defaults and keep sensitive data out of the client-side cookie entirely.

Secure Session Configuration

Configure Chi sessions with secure flags and server-side storage to prevent cookie theft and exposure. Avoid storing any credential-like data in the session.

(ns my-app.core
  (:require [hiccup.core :refer [html]]
            [ring.middleware.session.cookie :refer [cookie-store]]
            [ring.middleware.session :refer [wrap-session]]))

(def secure-session-store
  (cookie-store {:key "64-byte-secure-key-used-here-1234567890123456"
                 :cookie-attrs {:secure true
                                :http-only true
                                :same-site :strict
                                :max-age 3600}}))

(def app
  (-> my-handler
      (wrap-session {:store secure-session-store})))

Avoid Storing API Keys in Session

Never place API keys or secrets into the session map. Instead, store them in environment variables or a secure configuration service and reference them directly in handlers without session involvement.

(ns my-app.routes.dashboard
  (:require [compojure.core :refer [GET defroutes]]))

(def api-key (System/getenv "EXTERNAL_API_KEY"))

(defn safe-handler [request]
  (let [user-id (:user-id request)]
    {:status 200
     :body (str "User: " user-id " — key configured securely")}))

(defroutes app-routes
  (GET "/dashboard" [] safe-handler))

Validate and Sanitize Session Data

If session data must be used for non-sensitive purposes, ensure that any serialization or logging excludes sensitive fields. Use selective filtering when exposing session-derived information.

(defn filtered-session [session]
  (select-keys session [:user-id :role]))

(defn handler [request]
  {:status 200
   :body (filtered-session (:session request))})

Enforce Transport Security

Always use HTTPS and enforce secure cookie transmission. Chi applications behind proxies should ensure that the proxy sets the correct protocol so that :secure cookies are honored.

((-> app
     (wrap-session {:store (cookie-store {:cookie-attrs {:secure true}})}))
  request)

These practices align with middleBrick’s checks for Encryption and Data Exposure, ensuring that session cookies do not become vectors for API key leakage. By combining secure configuration with disciplined handling of credentials, Chi applications can mitigate the risks associated with combining session cookies and API key management.

Frequently Asked Questions

Can session cookies alone lead to API key exposure in Chi applications?
Yes, if API keys are stored within the session data and the session cookie is intercepted or misconfigured, an attacker can retrieve those keys. Always avoid storing secrets in sessions and protect cookies with secure, http-only, and same-site attributes.
How does middleBrick detect API key exposure involving session cookies?
middleBrick scans unauthenticated endpoints and analyzes session-related responses for potential data exposure. It flags routes that may leak session data and correlates findings with insecure cookie attributes or missing transport protections.