HIGH phishing api keysfastapicockroachdb

Phishing Api Keys in Fastapi with Cockroachdb

Phishing Api Keys in Fastapi with Cockroachdb — how this specific combination creates or exposes the vulnerability

When an API built with Fastapi uses Cockroachdb as the backing data store, the way application code handles, transmits, and logs API keys can create phishing risks even if the database itself is not directly compromised. A common pattern is for Fastapi routes to accept an API key from a client, forward it to external services, and persist selected metadata in Cockroachdb for auditing or rate-limiting. If the route does not strictly validate the source of the key, an attacker can submit a victim’s key via crafted requests, and the application may reflect or log that key in responses, logs, or error messages that an attacker can phish.

Specific risks in this combination include insecure direct object references (IDOR) where an endpoint accepts an identifier and a key and inadvertently associates the key with the wrong tenant, and improper handling of secrets in logs or trace data that Cockroachdb may store. For example, if a Fastapi route does something like cursor.execute("INSERT INTO key_usage (key_id, owner) VALUES ($1, $2)", (key_id, owner)) without verifying that the authenticated caller owns that key, an attacker can submit another user’s key and observe behavioral differences or error messages that reveal whether the key was accepted. Additionally, if the Fastapi app logs the raw key or includes it in structured logs that Cockroachdb retains, those logs become high-value targets for phishing or credential harvesting attacks.

Another vector is reflected or stored XSS in admin dashboards or debugging endpoints that query Cockroachdb for recent key usage and render results without proper escaping. An attacker could trick a privileged user into visiting a malicious page that calls the Fastapi endpoint with a forged key, and if the admin UI displays key-related data pulled from Cockroachdb without sanitization, the attacker may phish session tokens or keys via the UI. Because the scan checks input validation and data exposure, it can surface cases where API keys appear in responses or logs, highlighting the phishing surface introduced by this stack.

OpenAPI spec analysis is important here: if the spec defines a key parameter but does not clarify that it must never be returned in responses or logged, and runtime probes confirm that keys can be echoed in error bodies or introspection endpoints, the scanner will flag data exposure and insufficient input validation. This illustrates how the combination of Fastapi, Cockroachdb, and improper secret handling creates a phishing-friendly environment where exposed keys can be reused or phished from logs or UI elements.

Cockroachdb-Specific Remediation in Fastapi — concrete code fixes

Remediation centers on strict validation, scoping queries to the authenticated context, and avoiding any leakage of raw keys into logs, responses, or error messages. Below are concrete Fastapi examples using Cockroachdb with parameterized queries and tenant-aware checks.

from fastapi import Fastapi, Depends, HTTPException, status, Request
import psycopg2
from psycopg2.extras import RealDictCursor

app = Fastapi()

def get_db():
    # In production, use a connection pool and manage lifecycle appropriately
    conn = psycopg2.connect(
        host="your-cockroachdb-host",
        port="26257",
        dbname="yourdb",
        user="youruser",
        password="yourpassword",
        sslmode="require",
    )
    try:
        yield conn
    finally:
        conn.close()

def tenant_id_of(request: Request) -> str:
    # Example: derive tenant from subdomain or auth token; keep this authoritative
    return request.headers.get("X-Tenant-ID")

@app.post("/use-key")
async def use_key(request: Request, key_id: str, db: psycopg2.extensions.connection = Depends(get_db)):
    tenant = tenant_id_of(request)
    if not tenant:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="missing tenant")
    with db.cursor(cursor_factory=RealDictCursor) as cur:
        # Verify ownership before use: scope by tenant and key_id
        cur.execute(
            "SELECT key_id FROM tenant_keys WHERE tenant_id = %s AND key_id = %s FOR SHARE",
            (tenant, key_id)
        )
        row = cur.fetchone()
        if not row:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="key not found or access denied")
        # Safe usage: key material should never be selected here; only metadata
        cur.execute(
            "INSERT INTO key_usage (tenant_id, key_id, action) VALUES (%s, %s, %s)",
            (tenant, key_id, "used")
        )
        db.commit()
    return {"status": "ok"}

@app.get("/keys/{key_id}")
async def get_key_metadata(key_id: str, request: Request, db: psycopg2.extensions.connection = Depends(get_db)):
    tenant = tenant_id_of(request)
    if not tenant:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="missing tenant")
    with db.cursor(cursor_factory=RealDictCursor) as cur:
        cur.execute(
            "SELECT key_id, created_at, scope FROM tenant_keys WHERE tenant_id = %s AND key_id = %s",
            (tenant, key_id)
        )
        row = cur.fetchone()
        if row is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="not found")
        # Never return raw key material; only safe metadata
        return {k: v for k, v in row.items() if k != "raw_key"}

Key remediation practices illustrated:

  • Always scope Cockroachdb queries by tenant_id derived from an authoritative source (subdomain, JWT claim) and never trust client-supplied identifiers alone.
  • Use parameterized queries with placeholders (e.g., %s with psycopg2) to prevent injection and ensure type safety.
  • Select only metadata; never SELECT or log raw key material. If you store keys, store them encrypted at rest and avoid exposing them via endpoints.
  • Avoid logging raw keys; if structured logging is required, sanitize values before emitting logs that Cockroachdb might retain.
  • Apply principle of least privilege to database roles used by Fastapi so that the app cannot read or write unrelated tenants’ data.
  • Ensure OpenAPI definitions do not mark key parameters as responses; use responseClass or omit to reduce accidental exposure in generated docs.

These steps align the stack with secure handling expectations and reduce the phishing surface exposed by the Fastapi-Cockroachdb integration.

Frequently Asked Questions

Can middleBrick detect exposed API keys in responses when using Fastapi with Cockroachdb?
Yes, middleBrick’s data exposure checks can identify whether API keys appear in HTTP responses, logs, or error messages, which helps surface phishing risks in this stack.
Does middleBrick test authentication and input validation for Fastapi endpoints that use Cockroachdb?
Yes, middleBrick runs parallel checks including Authentication and Input Validation, which are relevant for Fastapi endpoints that interact with Cockroachdb and handle secrets like API keys.