HIGH ssrf server sidefastapicockroachdb

Ssrf Server Side in Fastapi with Cockroachdb

Ssrf Server Side in Fastapi with Cockroachdb — how this specific combination creates or exposes the vulnerability

Server-side request forgery (SSRF) in a FastAPI service that uses CockroachDB can arise when an endpoint accepts a user-supplied URL or host and uses it to form a database connection or an outbound HTTP request. CockroachDB connection strings often contain network location details, and if an attacker can influence the target host or port, they may force the server to open unintended connections. For example, a FastAPI endpoint that builds a CockroachDB SQL connection from a user-provided parameter can be abused to reach internal services, metadata endpoints (like 169.254.169.254 on cloud environments), or external hosts that the backend should not contact.

Consider a scenario where an API accepts a database address to support multi-tenant routing or migrations. If the endpoint does not strictly validate or whitelist hosts and simply forwards the value into a CockroachDB connection string, SSRF becomes feasible. Attackers can supply internal IPs, cloud metadata URLs, or even HTTP-based database proxy endpoints to make the server perform network actions on their behalf. Because FastAPI applications often run with broad network access in containerized or cloud environments, the potential reach includes internal infrastructure and metadata services.

When combined with CockroachDB, SSRF can also amplify data exposure if the attacker-controlled target returns sensitive rows or schema information. For instance, directing queries to an internal admin endpoint or a compromised service can return rows that would otherwise be unreachable. Moreover, if the application uses features like external storage integrations or changefeeds that initiate outbound connections, an SSRF vector may allow an attacker to pivot into those flows. Because the vulnerability is about the server initiating connections, the issue resides in how the API constructs and uses connection parameters, not in CockroachDB itself.

middleBrick detects SSRF as one of its 12 parallel security checks. When scanning a FastAPI endpoint that interacts with CockroachDB, it tests whether user-influenced inputs can cause the server to reach unexpected internal or external destinations. The scanner does not rely on internal architecture; it observes network behavior and flags endpoints that make connections to private or sensitive targets. This is especially relevant when OpenAPI specs describe parameters that influence connection strings or HTTP clients, and runtime probes confirm that those parameters reach beyond the intended network boundaries.

Cockroachdb-Specific Remediation in Fastapi — concrete code fixes

Remediation focuses on strict input validation, connection parameter isolation, and avoiding dynamic host composition. Do not construct CockroachDB connection strings from user input. Instead, use configuration management to select among pre-approved connection profiles, and enforce allowlists for hosts and ports. When dynamic database routing is required, map user identifiers to predefined connection strings server-side rather than accepting raw network locations.

Below are concrete, working examples for FastAPI with CockroachDB that demonstrate safe patterns.

  • Safe connection management with an allowlist:
from fastapi import FastAPI, HTTPException, Query
import psycopg2
from psycopg2 import sql

ALLOWED_ZONES = {"us-east1", "eu-west1", "test-zone"}

def get_connection_string(zone: str) -> str:
    if zone not in ALLOWED_ZONES:
        raise ValueError("Zone not allowed")
    # Use environment variables or a secure config service for credentials
    return f"postgresql://user:password@{zone}-crdb.example.com:26257/defaultdb?sslmode=require"

app = FastAPI()

@app.get("/query")
def run_query(zone: str = Query(..., description="Predefined deployment zone")):
    conn_str = get_connection_string(zone)
    conn = psycopg2.connect(conn_str)
    try:
        with conn.cursor() as cur:
            cur.execute("SELECT NOW()")
            result = cur.fetchone()
            return {"zone": zone, "server_time": result[0]}
    finally:
        conn.close()
  • Validating host components when constructing network locations:
from pydantic import validator, BaseModel
from typing import Literal

class DBRequest(BaseModel):
    cluster: Literal["primary", "analytics"]
    region: str

    @validator("region")
    def region_whitelist(cls, v):
        allowed = {"us-east1", "us-west1", "eu-central1"}
        if v not in allowed:
            raise ValueError("region not allowed")
        return v

def build_safe_dsn(request: DBRequest) -> str:
    host_map = {
        "primary": "primary-{region}-crdbs.example.com",
        "analytics": "analytics-{region}-crdbs.example.com",
    }
    host = host_map[request.cluster].format(region=request.region)
    return f"postgresql://user:password@{host}:26257/defaultdb?sslmode=require"
  • Using environment-based profiles instead of runtime composition:
import os
from fastapi import Depends

def get_db_url():
    url = os.getenv("COCKROACHDB_URL")
    if not url:
        raise RuntimeError("Missing database URL configuration")
    return url

@app.get("/health")
def health(db_url: str = Depends(get_db_url)):
    conn = psycopg2.connect(db_url)
    conn.close()
    return {"status": "ok"}

These patterns ensure that user input never directly specifies network destinations, effectively mitigating SSRF risks while still allowing flexible deployment topologies. middleBrick’s scans can validate that endpoints reject or safely map unexpected zone or region parameters, confirming that the unauthenticated attack surface does not permit arbitrary network connections.

Frequently Asked Questions

Can SSRF in FastAPI with CockroachDB lead to metadata service access?
Yes, if user-influenced parameters allow connections to cloud metadata endpoints (e.g., 169.254.169.254), SSRF can expose metadata. Prevent this by rejecting non-whitelisted hosts and using fixed connection profiles.
Does middleBrick fix SSRF findings in FastAPI apps with CockroachDB?
middleBrick detects and reports SSRF with remediation guidance, but it does not fix or block findings. Developers must implement validation, allowlists, and secure configuration changes based on the reported guidance.