HIGH token leakageaxumcockroachdb

Token Leakage in Axum with Cockroachdb

Token Leakage in Axum with Cockroachdb — how this specific combination creates or exposes the vulnerability

Token leakage in an Axum service that uses CockroachDB can occur when authentication tokens, session identifiers, or API keys are inadvertently exposed in logs, error messages, or through database interactions. Axum, a web application framework for Rust, encourages structured request handling, but developers may inadvertently pass sensitive token values into database queries or responses. CockroachDB, a distributed SQL database, does not inherently leak tokens, but the way an Axum application constructs queries or handles errors can expose these values.

One common pattern is logging incoming request headers or authentication tokens for debugging purposes. If an Axum handler logs the Authorization header before validating or forwarding it to CockroachDB, the token may appear in application logs, monitoring systems, or error traces. This is particularly risky in distributed environments where logs are aggregated centrally.

Another vector involves error handling when CockroachDB queries fail. For example, if an Axum handler uses the expect or unwrap methods on database results and a token is included in the error context or message, the token can be exposed in stack traces or HTTP error responses. Consider a route that fetches user data based on a token:

async fn get_user_info(
    pool: web::Data>,
    token: String,
) -> Result {
    let conn = pool.get().await.map_err(|e| {
        // Risk: including token in error message
        (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {}, token: {}", e, token))
    })?;
    // ... query logic
}

In this example, if the database connection fails, the token is embedded in the error message returned to the client, creating a direct leakage path. Even if the token is not returned to the client, structured logging that captures the error may retain the token, especially if the logging layer serializes the full error context.

Additionally, token leakage can arise from improper use of query parameters or dynamic SQL construction in Axum handlers that interact with CockroachDB. If a token is passed as a query parameter and then reflected in logs, metrics, or error responses without sanitization, it becomes accessible to unauthorized parties. CockroachDB's support for prepared statements helps mitigate some risks, but the application layer must ensure tokens are never included in log lines or diagnostic output.

Using the middleBrick CLI to scan an Axum service that connects to CockroachDB can help detect these leakage patterns by analyzing endpoint behavior and response handling. The scanner checks for tokens appearing in error messages, logs, or unauthenticated endpoints, providing remediation guidance that aligns with the OWASP API Top 10 and common security best practices for Rust web services.

Cockroachdb-Specific Remediation in Axum — concrete code fixes

To prevent token leakage in an Axum application using CockroachDB, implement strict separation between authentication data and database operations. Use middleware to validate and sanitize tokens before they reach business logic or database layers. Avoid including tokens in error messages, logs, or query parameters.

First, ensure tokens are handled in a dedicated layer that does not propagate them into database contexts. For example, extract the token in an extractor and immediately validate it against a secure store without echoing it in logs:

async fn validate_token(
    token: String,
    pool: web::Data>,
) -> Result<Uuid, (StatusCode, String)> {
    let conn = pool.get().await.map_err(|e| {
        (StatusCode::INTERNAL_SERVER_ERROR, "Database connection failed".to_string())
    })?;

    // Use a prepared statement to avoid SQL injection and prevent token reflection
    let user_id: Uuid = conn
        .query_one(
            "SELECT user_id FROM api_tokens WHERE token = $1",
            &[&token],
        )
        .await
        .map_err(|e| {
            (StatusCode::UNAUTHORIZED, "Invalid token".to_string())
        })?
        .get(0);

    Ok(user_id)
}

This approach avoids including the token in any error message returned to the client. The token is used only as a parameter in a prepared statement, reducing the risk of injection and accidental exposure.

Second, configure logging to filter or redact sensitive fields. In Axum, you can use tracing with layer filters to exclude token values:

use tracing_subscriber::filter::EnvFilter;

fn setup_logging() {
    let filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new("info"));
    tracing_subscriber::fmt()
        .with_filter(filter)
        .without_time()
        .init();
}

Third, ensure that CockroachDB interactions use parameterized queries exclusively. Avoid string interpolation when constructing SQL statements. For example, instead of:

// Unsafe: string interpolation
let query = format!("SELECT * FROM users WHERE token = '{}'", token);

Use:

// Safe: parameterized query
conn.query_one("SELECT * FROM users WHERE token = $1", &[&token]).await?;

Finally, apply middleware that strips sensitive headers from logs and responses. In Axum, you can wrap your routes with a layer that redacts known token headers before they are processed by logging utilities. This aligns with the security checks provided by middleBrick, which scans for token leakage and provides prioritized remediation steps mapped to compliance frameworks such as OWASP API Top 10 and SOC2.

For teams using the Pro plan, continuous monitoring can be enabled to detect token leakage patterns across deployed Axum services connecting to CockroachDB. The GitHub Action can fail builds if risk scores exceed defined thresholds, ensuring that leakage-prone patterns are caught before deployment.

Frequently Asked Questions

How can I test if my Axum service leaks tokens to CockroachDB?
Use the middleBrick CLI to scan your endpoint: middlebrick scan https://your-api.example.com. The scanner checks for tokens in error messages, logs, and unauthenticated paths. Review the report for high-severity findings related to token leakage and follow the provided remediation guidance.
Does middleBrick fix token leakage issues automatically?
middleBrick detects and reports token leakage with detailed remediation guidance, but it does not automatically fix or patch issues. Developers must apply the recommended fixes, such as removing tokens from error messages and using parameterized queries with CockroachDB.