HIGH missing authenticationactixcockroachdb

Missing Authentication in Actix with Cockroachdb

Missing Authentication in Actix with Cockroachdb — how this specific combination creates or exposes the vulnerability

When an Actix web service connects directly to a CockroachDB cluster without enforcing authentication on its API layer, it can expose an unauthenticated attack surface even if the database itself requires credentials. middleBrick scans the reachable API endpoints and, in the Authentication check, detects that endpoints performing database operations do not validate the caller’s identity before constructing and executing SQL statements. This situation commonly arises when route handlers forward requests directly to CockroachDB using a shared server-side connection or an ORM session initialized with a privileged account, and the handler omits any token or session verification.

For example, an Actix route like /api/users/{user_id} might build a SQL query using the user_id from the path without confirming the request includes a valid session or API key. Because the scan tests the unauthenticated attack surface, middleBrick can invoke the endpoint without credentials, observe the response, and determine whether the endpoint returns data or errors. If the handler returns user data or internal errors that reveal database structure, the Authentication check flags a finding. The BOLA/IDOR check may further flag the issue when different users can access or modify other users’ resources by simply changing the user_id path parameter.

Because CockroachDB supports PostgreSQL protocol, an Actix service might use a connection pool initialized with a high-privilege role. If the application does not enforce per-request authorization, an unauthenticated caller can indirectly leverage that pooled connection to run queries. middleBrick’s Property Authorization and Input Validation checks examine whether the handler sanitizes and validates input before using it in SQL, and whether authorization logic is consistently applied across routes. In this context, missing authentication often correlates with missing or inconsistent authorization checks, increasing the likelihood of data exposure or privilege escalation.

Cockroachdb-Specific Remediation in Actix — concrete code fixes

To address missing authentication and related authorization gaps, ensure each Actix route that interacts with CockroachDB validates identity and applies least-privilege database access. Below are concrete, realistic code examples using the sqlx crate with CockroachDB’s PostgreSQL wire protocol.

1. Enforce authentication before database access

Add an extractor or middleware that verifies an API key or session before allowing the handler to run.

use actix_web::{web, HttpResponse, Result};
use sqlx::PgPool;

async fn get_user_info(
    pool: web::Data<PgPool>,
    user_id: web::Path<i32>,
    auth: web::Header<String>, // e.g., bearer token or API key
) -> Result<HttpResponse> {
    let token = auth.into_inner();
    if !is_valid_token(&token).await {
        return Ok(HttpResponse::Unauthorized().finish());
    }

    let user: (String,) = sqlx::query_as("SELECT username FROM users WHERE id = $1")
        .bind(*user_id)
        .fetch_one(pool.get_ref())
        .await
        .map_err(|e| actix_web::error::ErrorInternalServerError(e))?;

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

async fn is_valid_token(token: &str) -> bool {
    // Implement token verification against your identity provider or store
    !token.is_empty()
}

2. Use per-request roles or tenant-aware queries

Initialize a pool with a low-privilege role, and scope queries by tenant or user ID to enforce row-level security.

use sqlx::postgres::PgConnectOptions;
use std::env;

fn create_pool() -> sqlx::PgPool {
    let database_url = env::var("COCKROACHDB_URL").expect("COCKROACHDB_URL must be set");
    let mut opts = PgConnectOptions::from_str(&database_url).unwrap();
    // Use a role with read-only or limited write permissions per service
    opts.username("api_reader")
        .password("strong_password_here")
        .database("api_db");
    sqlx::postgres::PgPoolOptions::new()
        .max_connections(5)
        .connect_lazy(&opts)
}

3. Apply input validation and parameterized queries

Never concatenate user input into SQL strings. Always use bind parameters to prevent injection and ensure type safety.

async fn update_user_email(
    pool: web::Data<PgPool>,
    user_id: web::Path<i32>,
    body: web::Json<EmailUpdate>,
    auth: web::Header<String>,
) -> Result<HttpResponse> {
    let token = auth.into_inner();
    if !is_valid_token(&token).await {
        return Ok(HttpResponse::Unauthorized().finish());
    }

    let email = body.email.trim();
    if email.is_empty() || email.len() > 254 {
        return Ok(HttpResponse::BadRequest().body("Invalid email"));
    }

    sqlx::query(
        "UPDATE users SET email = $1 WHERE id = $2 AND owner_id = (SELECT id FROM auth WHERE token = $3)",
    )
    .bind(email)
    .bind(*user_id)
    .bind(&token)
    .execute(pool.get_ref())
    .await
    .map_err(|e| actix_web::error::ErrorInternalServerError(e))?;

    Ok(HttpResponse::Ok().finish())
}

4. Leverage CockroachDB’s role-based access control

Create roles in CockroachDB that match your API permissions, and connect Actix with the least-privileged role.

-- Example SQL executed by a DBA
CREATE ROLE api_reader WITH LOGIN PASSWORD 'reader_secret';
GRANT SELECT ON users, orders TO api_reader;

CREATE ROLE api_writer WITH LOGIN PASSWORD 'writer_secret';
GRANT SELECT, INSERT, UPDATE ON users, orders TO api_writer;
REVOKE ALL ON DATABASE api_db FROM api_writer;

Then in your connection options, use api_reader or api_writer depending on the route’s required permissions.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

Does middleBrick fix missing authentication issues in Actix with Cockroachdb?
No. middleBrick detects and reports missing authentication and related security findings, including remediation guidance. It does not fix, patch, or block issues.
Can I test authenticated endpoints only during a middleBrick scan?
middleBrick tests the unauthenticated attack surface by default. To include authenticated testing, provide credentials or authentication details if supported by the scan configuration options available in the product you use, such as the CLI or Dashboard.