HIGH api key exposurefastapisession cookies

Api Key Exposure in Fastapi with Session Cookies

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

When an API key is handled together with session cookies in a FastAPI application, the risk is that either the key or the session cookie is exposed through insecure transport, improper storage, or accidental leakage in logs and error messages. API keys are typically long-lived secrets used to control access and quota, while session cookies maintain user authentication state. If either is transmitted over non-HTTPS connections, captured in browser developer tools, stored in insecure locations, or reflected in responses, an attacker can escalate their access or impersonate users.

FastAPI does not inherently expose API keys or session cookies, but application design choices can create exposure. For example, returning API keys in JSON responses, logging them via middleware, including them in URLs as query parameters, or failing to set secure cookie attributes (Secure; HttpOnly; SameSite) can lead to exposure. Session cookies without HttpOnly are accessible to JavaScript, enabling theft via XSS. Without Secure, cookies can be sent over HTTP, making them interceptable. Missing or weak SameSite settings can expose cookies to CSRF-aided leakage in cross-origin contexts. Inadequate key rotation and unclear boundaries between key usage and session usage further increase risk.

Consider an endpoint that echoes headers for debugging or that embeds the API key in frontend JavaScript. An attacker who can read the page source or trigger an error disclosure may obtain the key. Similarly, if session cookies are not bound to a strict scope (path, domain) and are long-lived, session fixation or token replay becomes feasible. In a microservice mesh where headers are forwarded, failing to strip or protect sensitive headers can propagate the key or cookie beyond the intended boundary. OWASP API Top 10 items such as Broken Object Level Authorization and Security Misconfiguration are relevant when access controls around keys and cookies are weak.

middleBrick scans unauthenticated attack surfaces and will flag findings such as missing Secure or HttpOnly flags, key exposure in responses or logs, and missing transport protections. It performs checks across Data Exposure, Input Validation, Authentication, and Security Misconfiguration, correlating spec definitions with runtime behavior. For example, it can detect if an OpenAPI spec describes cookie-based auth but runtime responses inadvertently include API keys in JSON payloads. These findings are provided with severity and remediation guidance rather than attempting to fix the service.

Session Cookies-Specific Remediation in Fastapi — concrete code fixes

Secure session cookies in FastAPI require explicit configuration of cookie attributes and disciplined handling of secrets. Below are concrete, working examples that you can adopt to reduce exposure.

Secure cookie settings with FastAPI and Starlette

Set cookie attributes to protect transport and storage. Use Secure to ensure transmission only over HTTPS, HttpOnly to prevent JavaScript access, and appropriate SameSite to limit cross-origin sends.

from fastapi import FastAPI, Response, Cookie
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/login")
async def login(response: Response):
    response.set_cookie(
        key="session_id",
        value="",
        httponly=True,
        secure=True,
        samesite="lax",
        max_age=3600,
        path="/",
    )
    return {"message": "Logged in"}

@app.get("/clear")
async def clear_session(response: Response):
    response.delete_cookie(
        key="session_id",
        httponly=True,
        secure=True,
        samesite="lax",
        path="/",
    )
    return {"message": "Logged out"}

Avoid exposing API keys in responses or logs

Never include raw API keys in JSON bodies or headers returned to clients. If a key must be referenced, use opaque tokens or session identifiers. Sanitize logs to ensure keys are not written. Example of safe header usage without leaking the key:

from fastapi import FastAPI, Header, HTTPException
import os

app = FastAPI()
API_KEY = os.getenv("API_KEY")

@app.get("/resource")
async def get_resource(x_api_key: str = Header(None)):
    if x_api_key != API_KEY:
        raise HTTPException(status_code=403, detail="Invalid key")
    return {"data": "protected"}

Transport and deployment hygiene

Always enforce HTTPS in production by using a reverse proxy or load balancer that terminates TLS. Do not pass API keys or session cookies in URLs. Configure CORS narrowly to limit origins and methods. Use environment variables or a secrets manager for configuration, and rotate keys on a defined schedule. Validate input rigorously to reduce injection paths that could lead to cookie or key leakage.

How middleBrick helps identify gaps

middleBrick can highlight insecure cookie practices and header handling by comparing the OpenAPI spec with runtime responses. It checks for transport protections, cookie attributes, and potential key exposure across Data Exposure, Authentication, and Security Misconfiguration checks. The findings include severity and remediation guidance to help you address issues without changing your core logic.

Frequently Asked Questions

Can session cookies alone protect an API key in FastAPI?
No. Session cookies manage user sessions but do not protect API keys. API keys should be stored server-side, transmitted only over HTTPS, and never echoed to the client. Use the Secure; HttpOnly; SameSite cookie attributes and keep keys out of browser-accessible storage.
What should I do if middleBrick flags API key exposure in a response?
First, confirm the finding by reviewing the response payload, logs, and error messages. Remove the key from responses, sanitize logs, and ensure keys are sourced from environment variables or a secrets manager. Re-scan to verify the exposure is resolved and maintain strict boundaries between authentication tokens and session identifiers.