HIGH api key exposureactixcockroachdb

Api Key Exposure in Actix with Cockroachdb

Api Key Exposure in Actix with Cockroachdb — how this specific combination creates or exposes the vulnerability

When an Actix web service connects to Cockroachdb and exposes an API key, the risk typically arises from how the application handles, logs, or transmits credentials across the database and HTTP layers. In this combination, an API key may be embedded in connection strings, query parameters, or request headers that are inadvertently exposed through logs, error messages, or misconfigured middleware.

Actix routes often forward requests to Cockroachdb using pooled connections. If the API key is passed as a query parameter or stored in environment variables without proper masking, scanning endpoints that interact with the database can reveal these values. For example, debug endpoints or verbose error responses may serialize database connection details, including the key, into JSON or HTML output.

Another exposure path occurs when the Actix application constructs SQL queries by string interpolation instead of using prepared statements. An attacker probing endpoints that interact with Cockroachdb might trigger errors that disclose the connection string or key through stack traces. Additionally, if the application logs every request and response, including headers that contain the API key, those logs become a persistent leakage vector accessible to anyone with log access.

Consider an endpoint that retrieves user data and passes an API key as a Bearer token in an Authorization header. If the Actix handler does not strip sensitive headers before logging, a scan testing Data Exposure will flag the header as leaked. The scanner can detect the key in clear text within HTTP logs or within error payloads returned by Cockroachdb when syntax or permission errors occur.

SSRF-related checks are particularly relevant here. If an Actix route accepts a URL input that is used to query Cockroachdb over HTTP or external APIs, an attacker might coerce the service to send requests that include the API key in outbound headers. The LLM/AI Security checks in middleBrick can detect whether system prompts or configuration snippets containing keys are echoed in model outputs or logs, highlighting indirect exposure through AI-assisted tooling.

Because middleBrick tests unauthenticated attack surfaces, it can identify endpoints where API keys are reflected in responses without authentication. This includes introspection or version endpoints that return environment details, configuration snippets, or database metadata that inadvertently include the key used for Cockroachdb connectivity.

Cockroachdb-Specific Remediation in Actix — concrete code fixes

To mitigate API key exposure in an Actix application using Cockroachdb, adopt strict separation between code, configuration, and runtime secrets. Use environment variables injected at deployment time rather than hardcoding keys in source files or connection strings. Always use prepared statements to avoid SQL-based leakage and ensure that error handling does not expose internal details.

Secure Connection Setup with TLS and Parameterized Queries

Establish a secure connection to Cockroachdb using TLS and avoid embedding keys in URLs. Instead, load the key from a secure source and pass it as a parameter to the connection builder.

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use cockroachdb_rs::Client;
use std::env;

async fn get_user_data(path: web::Path) -> impl Responder {
    let db_url = env::var("COCKROACH_URL").expect("COCKROACH_URL must be set");
    let api_key = env::var("COCKROACH_API_KEY").expect("COCKROACH_API_KEY must be set");

    // Use a secure client with TLS; do not concatenate the key into the URL
    let client = Client::new(&db_url)
        .with_ssl(true)
        .with_auth_token(&api_key)
        .connect()
        .await
        .map_err(|e| actix_web::error::ErrorInternalServerError(e))?;

    let user_id = path.into_inner();
    // Use parameterized queries to prevent SQL injection and avoid key exposure in logs
    let row = client
        .query_one("SELECT email, created_at FROM users WHERE id = $1", &[&user_id])
        .await
        .map_err(|e| actix_web::error::ErrorBadRequest(e))?;

    HttpResponse::Ok().json(row)
}

Header and Logging Sanitization

Ensure that request headers containing API keys are not logged. Implement a logging wrapper that strips sensitive headers before output is written.

use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::Error;
use std::future::{ready, Ready};

pub struct SensitiveHeaderFilter;

impl Transform for SensitiveHeaderFilter
where
    S: Service, Error = Error>,
{
    type Response = ServiceResponse;
    type Error = Error;
    type InitError = ();
    type Transform = HeaderFilterMiddleware;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(HeaderFilterMiddleware { service }))
    }
}

pub struct HeaderFilterMiddleware<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for HeaderFilterMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
    fn call(&self, req: ServiceRequest) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<ServiceResponse<B>, Error>>> {
        // Remove sensitive headers before logging or passing downstream
        req.headers_mut().remove("X-API-Key");
        let fut = self.service.call(req);
        Box::pin(async move {
            let res = fut.await?;
            Ok(res)
        })
    }
}

Error Handling to Prevent Data Leakage

Customize error responses to avoid returning database details that might contain or hint at the API key. Use generic messages and log detailed errors internally without exposing them to the client.

async fn safe_query() -> Result<(), actix_web::Error> {
    let result = std::panic::catch_unwind(|| {
        // Cockroachdb operation that might fail
    });

    match result {
        Ok(_) => Ok(()),
        Err(_) => {
            // Do not include internal error details in the response
            Err(actix_web::error::ErrorInternalServerError("An internal error occurred"))
        }
    }
}

By combining secure credential handling, parameterized queries, and careful logging, the Actix and Cockroachdb stack can avoid unintentional API key exposure in both runtime and diagnostic outputs.

Frequently Asked Questions

Can middleBrick detect an exposed API key in Actix responses without authentication?
Yes, middleBrick scans unauthenticated endpoints and can identify API keys reflected in HTTP responses, logs, or error payloads when testing the attack surface of an Actix service integrated with Cockroachdb.
Does middleBrick’s LLM/AI Security check help identify indirect API key exposure through AI tooling?
Yes, it detects system prompt leakage and active prompt injection attempts that could reveal configuration details or keys, including scenarios where an API key appears in logs or is echoed by LLM-assisted development workflows.