HIGH cors wildcardaxumcockroachdb

Cors Wildcard in Axum with Cockroachdb

Cors Wildcard in Axum with Cockroachdb — how this specific combination creates or exposes the vulnerability

A CORS wildcard (Access-Control-Allow-Origin: *) in an Axum service that also interacts with CockroachDB can unintentionally expose authenticated or sensitive endpoints to any origin. When credentials or authorization headers are required, browsers block responses with a wildcard, but misconfigured routes may still allow credentialed requests from unexpected origins if preflight responses are too permissive.

In Axum, route-level CORS configuration may apply per-route or globally via middleware. If a route serving CockroachDB-backed data uses a wildcard while also requiring authentication (e.g., JWT in an Authorization header), the combination creates a mismatch: the CORS policy signals broad availability, but authentication is enforced at the handler. An attacker can craft a webpage on any domain to invoke authenticated requests via JavaScript, relying on browser CORS checks to pass, while the backend queries CockroachDB using the caller’s credentials or a compromised token.

Consider an Axum route that queries CockroachDB for user-specific records using a user ID from a JWT. If the CORS middleware sets Access-Control-Allow-Origin: * and allows credentials, a malicious site can trigger requests that the browser forwards with cookies or bearer tokens. CockroachDB may log connections tied to the compromised token, and the route may leak data belonging to other users if ownership checks are missing (BOLA/IDOR). The wildcard therefore amplifies the impact of missing resource-level authorization by making the endpoint reachable from arbitrary origins.

During a middleBrick scan, such a configuration may be flagged under Authentication, BOLA/IDOR, and Property Authorization checks. The scanner tests unauthenticated and authenticated origins to observe CORS headers and whether responses include sensitive data when credentials are supplied. Because the scan uses OpenAPI/Swagger spec analysis with full $ref resolution, it cross-references declared CORS settings against runtime behavior and database-related routes, highlighting mismatches between permissive CORS and backend data access patterns involving CockroachDB.

To address this safely, define explicit origins for services that query CockroachDB, especially when routes depend on user context or tokens. Combine strict CORS rules with strong ownership validation in handlers so that even if a request originates from an allowed domain, it can only access records the subject is permitted to see. MiddleBrick’s per-category breakdowns and prioritized findings can guide which routes require tightened CORS policies and which handlers need additional authorization checks.

Cockroachdb-Specific Remediation in Axum — concrete code fixes

Remediate by replacing the wildcard with specific origins and enforcing per-request authorization against CockroachDB records. Below is a minimal, working Axum example that integrates CORS with a PostgreSQL-compatible driver for CockroachDB, ensuring that each request validates ownership before returning data.

use axum::{routing::get, Router};
use cockroachdb_coap_client::CoapClient; // illustrative client
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use tower_http::cors::{CorsLayer, Any};

async fn get_user_data(
    pool: PgPool,
    user_id: String,
    auth_subject: String,
) -> Result {
    // Enforce ownership at the handler level
    let record: (String,) = sqlx::query_as("SELECT data FROM user_data WHERE user_id = $1 AND subject = $2")
        .bind(&user_id)
        .bind(&auth_subject)
        .fetch_one(&pool)
        .await
        .map_err(|_| (axum::http::StatusCode::NOT_FOUND, "Not allowed".to_string()))?;
    Ok(record.0)
}

#[tokio::main]
async fn main() {
    let pool: PgPool = PgPoolOptions::new()
        .connect(&std::env::var("COCKROACHDB_URL").expect("COCKROACHDB_URL must be set"))
        .await
        .expect("Failed to create pool");

    let cors = CorsLayer::new()
        .allow_origin(Any.into()) // Replace with specific origins in production
        .allow_methods(Any)
        .allow_headers(Any);

    let app = Router::new()
        .route("/users/:user_id", get(|user_id: String| async move {
            // auth_subject derived from JWT or session
            let auth_subject = "subject_from_token".to_string();
            get_user_data(pool, user_id, auth_subject).await
        }))
        .layer(cors);

    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

Key points in this example:

  • allow_origin should be set to explicit origins instead of a wildcard when handling authenticated requests to CockroachDB-backed routes.
  • The SQL query includes a subject = $2 condition that ties the database read to the authenticated subject, preventing horizontal privilege escalation across users.
  • CORS headers are applied at the middleware level, ensuring preflight responses do not grant broader access than intended.

For teams using the middleBrick ecosystem, the Pro plan’s continuous monitoring can be configured to alert when a route serving CockroachDB data permits a wildcard origin while also accepting credentials. The CLI can be integrated into scripts to enforce CORS policies before deployment, and the GitHub Action can fail builds if a scan detects overly permissive CORS settings on endpoints that interact with databases.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Can a CORS wildcard be safe if no authentication is required?
A wildcard may be acceptable for truly public, read-only endpoints that do not expose sensitive data or trigger state changes. However, when the endpoint queries CockroachDB or returns user-specific information, prefer explicit origins and validate ownership to reduce risk.
How does middleBrick detect CORS-related issues with CockroachDB endpoints?
middleBrick compares CORS headers reported at runtime against the OpenAPI/Swagger spec, including $ref resolution. It flags responses with a wildcard origin on routes that require authentication or access CockroachDB-backed resources, and it highlights missing ownership checks in handler logic.